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

我正在循环浏览几个追踪的excel文件的目录,并尝试一次刷新一个excel文件。 我不断收到这个错误,指出刷新操作仍然在文件A上运行,例如,FileB正在尝试启动刷新操作。 循环是快速的,不知何故,我必须等待文件A上的先前刷新操作才能开始刷新文件B.

未处理的exception:System.Runtime.InteropServices.COMException:消息filter指示应用程序正忙。 (来自HRESULTexception:0x8001010A(RPC_E_SERVERCALL_RETRYLATER))在Microsoft.Office.Interop.Excel._Workbook.RefreshAll()在RefreshExcelFiles.Program.RefreshFile(string文件名)

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

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); } } } 

我find了我的问题的答案。 我需要实现IMessageFilter RetryRejectedCall 。 对于使用IMessageFilter :: RetryRejectedCall的C#和VB.NET代码示例, 请参阅此博客post 。

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