在多线程C#应用程序中使用interop的Excel文件操作失败

时间:2015-05-31 19:08:10

标签: c# .net multithreading interop export-to-excel

我是一个自动执行某些文件相关作业的应用程序。每个作业都在不同的线程中执行。一种工作是将Excel文件导出为HTML格式。我为此目的使用Microsoft.Office.Interop.Excel命名空间。我的应用程序在Windows Server 2008环境下运行良好,但我们将服务器升级到Windows Server 2012,我开始收到以下错误:

  

消息过滤器指示应用程序正忙。 (来自HRESULT的异常:0x8001010A(RPC_E_SERVERCALL_RETRYLATER))

首先调用导出函数成功将Excel文件导出为HTML但连续调用失败并出现上述错误。我确保关闭并完成所有与Excel相关的对象,并从任务管理器检查excel.exe是否工作但没有运气。

如果发生此错误,我会使用以下代码重试,但它会继续获取异常并在5次重试后失败

while (!success)
            {
try
                {
                    ExportExcel();
                    success = true;
                    System.Threading.Thread.Sleep(2000);
                }
                catch (System.Runtime.InteropServices.COMException loE)
                {
                    tryCount++;
                    if (loE.HResult.ToString("X") == "80010001" || loE.HResult.ToString("X") == "8001010A" && tryCount<5)
                    {                                                                     
                      System.Threading.Thread.Sleep(2000);
                    }
                    else
                    {
                        throw;
                    }
                }
             }

我怀疑这可能与某些线程错误有关,但我无法得出答案。任何见解都会有所帮助。

感谢Joe指出正确的方法:

我最终使用了以下链接混合的解决方案:  http://blogs.artinsoft.net/Mrojas/archive/2012/09/28/Office-Interop-and-Call-was-rejected-by-callee.aspx

http://blogs.msdn.com/b/pfxteam/archive/2010/04/07/9990421.aspx

所以我使用了以下内容:

StaTaskScheduler cts=new StaTaskScheduler(1);
TaskFactory factory;          
factory = new TaskFactory(cts);
Task jobRunTask = factory.StartNew(() =>
{
   MessageFilter.Register();
   ExcelInteropFunction();
   MessageFilter.Revove();
 });

1 个答案:

答案 0 :(得分:2)

我相信Excel对象模型是单元线程的,因此来自多个线程的调用将被封送到Excel进程中的同一个线程 - 这可能很忙,特别是如果有多个客户端线程。

您可以实现IMessageFilter(OLE消息过滤器,不要与System.Windows.Forms.IMessageFilter混淆)以提供自定义重试逻辑。

您的服务器升级可能已更改时序特征,以便更频繁地发生问题。

<强>更新

以下是OLE消息过滤器的示例基本实现:

    // Definition of the IMessageFilter interface which we need to implement and 
    // register with the CoRegisterMessageFilter API.
    [ComImport(), Guid("00000016-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
    interface IOleMessageFilter // Renamed to avoid confusion w/ System.Windows.Forms.IMessageFilter
    {
        [PreserveSig]
        int HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo);
        [PreserveSig]
        int RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType);
        [PreserveSig]
        int MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType);
    }

    internal sealed class OleMessageFilter : IOleMessageFilter, IDisposable
    {
        [DllImport("ole32.dll")]
        private static extern int CoRegisterMessageFilter(IOleMessageFilter newFilter, out IOleMessageFilter oldFilter);

        private bool _isRegistered;
        private IOleMessageFilter _oldFilter;

        public OleMessageFilter()
        {
            Register();
        }

        private void Register()
        {
            // CoRegisterMessageFilter is only supported on an STA thread.  This will throw an exception
            // if we can't switch to STA
            Thread.CurrentThread.SetApartmentState(ApartmentState.STA);

            int result = CoRegisterMessageFilter(this, out _oldFilter);
            if (result != 0)
            {
                throw new COMException("CoRegisterMessageFilter failed", result);
            }
            _isRegistered = true;
        }

        private void Revoke()
        {
            if (_isRegistered)
            {
                IOleMessageFilter revokedFilter;
                CoRegisterMessageFilter(_oldFilter, out revokedFilter);
                _oldFilter = null;
                _isRegistered = false;
            }
        }

        #region IDisposable Members

        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                // Dispose managed resources
            }
            // Dispose unmanaged resources
            Revoke();
        }

        void IDisposable.Dispose()
        {
            GC.SuppressFinalize(this);
            Dispose(true);
        }

        ~OleMessageFilter()
        {
            Dispose(false);
        }

        #endregion

        #region IOleMessageFilter Members

        int IOleMessageFilter.HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo)
        {
            return 0; //SERVERCALL_ISHANDLED
        }

        int IOleMessageFilter.RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType)
        {
            if (dwRejectType == 2) // SERVERCALL_RETRYLATER
            {
                return 200; // wait 200ms and try again
            }

            return -1; // cancel call
        }

        int IOleMessageFilter.MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType)
        {
            return 2; //PENDINGMSG_WAITDEFPROCESS
        }
        #endregion
    }

您还可以查看this sample,但它会显示一个提示,询问用户是否要重试,如​​果您的客户端是多线程且基于服务器,则可能不合适。