gpt4 book ai didi

C# Excel 互操作 - 如何测试互操作对象是否仍在工作并执行任务?

转载 作者:太空狗 更新时间:2023-10-30 00:42:37 25 4
gpt4 key购买 nike

我正在遍历包含多个 excel 文件的目录,并试图一次刷新一个 excel 文件。我不断收到此错误,这表明刷新操作仍在文件 A 上运行,例如,文件 B 正在尝试启动刷新操作。循环速度太快,不知何故,我必须等待文件 A 上的先前刷新操作完成,然后才能开始刷新文件 B。

Unhandled Exception: System.Runtime.InteropServices.COMException: The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER)) at Microsoft.Office.Interop.Excel._Workbook.RefreshAll() at RefreshExcelFiles.Program.RefreshFile(String fileName)

这是我的代码。在循环中开始处理新文件之前,如何等待刷新操作完成?或者,在开始新文件之前等待对 wb 对象的 marshal 释放操作完成?

using System;
using System.Configuration;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;

namespace RefreshExcelFiles
{
internal class Program
{
private static string _fileDirectory;
private static Application _excelApp;

private static void Main(string[] args)
{
_fileDirectory = ConfigurationManager.AppSettings["FileDirectory"];
_excelApp = new Application();
_excelApp.DisplayAlerts = false;

Console.WriteLine("starting to refresh files");
int i = 0;
int total = Directory.GetFiles(_fileDirectory).Length;

foreach (string file in Directory.GetFiles(_fileDirectory))
{
i += 1;
Console.WriteLine("File " + file + " " + i.ToString() + "/" + total.ToString());
RefreshFile(file);
}

_excelApp.Quit();
Marshal.FinalReleaseComObject(_excelApp);

Console.WriteLine("press any key to exit");
Console.ReadLine();
}

private static void RefreshFile(string fileName)
{
_Workbook wb = _excelApp.Workbooks.Open(fileName, false);
wb.RefreshAll();

wb.Save();
wb.Close(Type.Missing, Type.Missing, Type.Missing);

Marshal.FinalReleaseComObject(wb);
}
}
}

最佳答案

我找到了问题的答案。我需要 implement IMessageFilter RetryRejectedCall .对于使用 IMessageFilter::RetryRejectedCall 的 C# 和 VB.NET 代码示例,see this blog post (wayback machine archived link) .

如果您自己没有注册 MessageFilter(通过调用 CoRegisterMessageFilter),您将获得默认行为,如果调用失败被拒绝。 .Net 将故障 HRESULT 转换为异常。为了处理您尝试调用时服务器忙的可能性,您需要在您的客户端代码中实现 IMessageFilter::RetryRejectedCall 并注册消息过滤器。在大多数情况下,您只需要等待几秒钟,然后重试调用 - 通常,这段时间足以让 Word 完成它正在做的任何事情,以便它可以处理你的调用。

关于C# Excel 互操作 - 如何测试互操作对象是否仍在工作并执行任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14467510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com