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

Fre*_*ter 4 c# excel interop marshalling

我循环遍历几个Huncel excel文件的目录,并尝试一次刷新一个excel文件.我不断收到此错误,表示刷新操作仍在文件A上运行,例如,FileB正在尝试启动刷新操作.循环是快速的,不知怎的,我必须等待文件A上的先前刷新操作完成,然后才开始刷新文件B.

未处理的异常:System.Runtime.InteropServices.COMException:消息过滤器指示应用程序正忙.(来自HRESULT的异常:0x8001010A(RPC_E_SERVERCALL_RETRYLATER))位于RefreshExcelFiles.Program.RefreshFile(String fileName)的Microsoft.Office.Interop.Excel._Workbook.RefreshAll()

这是我的代码.在循环中开始处理新文件之前,如何等待刷新操作完成?或者,在开始新文件之前,等待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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Fre*_*ter 7

我找到了问题的答案.我需要实现IMessageFilter RetryRejectedCall.有关使用IMessageFilter :: RetryRejectedCall的C#和VB.NET代码示例,请参阅此博客文章.

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