【问题标题】:Outlook interop causes outlook to stall *after* event handler has finishedOutlook 互操作导致 Outlook 在事件处理程序完成后停止
【发布时间】:2013-02-01 21:47:04
【问题描述】:

我遇到了一个问题,如果我的应用程序忙/无响应/因断点暂停,即使我收到的邮件事件处理程序早已返回,它也会导致 Outlook 停止。

我整理了一个小测试用例:

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Outlook;

namespace OutlookPerfTest
{
    class Program
    {
        private static Application app;
        private static NameSpace ns;

        static void Main(string[] args)
        {
            Type olType = Type.GetTypeFromProgID("Outlook.Application", false);

            app = Activator.CreateInstance(olType) as Application;
            ns = app.GetNamespace("MAPI");
            ns.Logon(null, null, false, false);

            app.NewMailEx += app_NewMailEx;

            for (; ; )
            { Thread.Sleep(10000); }
        }

        static void app_NewMailEx(string EntryIDCollection)
        {
            Console.WriteLine("New mail event triggered, running on background worker...");
            var bg = new BackgroundWorker();
            bg.DoWork += bg_DoWork;
            bg.RunWorkerAsync(EntryIDCollection);
            Console.WriteLine("New mail event ended, returning");
        }

        static void bg_DoWork(object sender, DoWorkEventArgs e)
        {
            Thread.Sleep(5000);

            Console.WriteLine("New mail thread started");

            string EntryIDCollection = (string)e.Argument;

            foreach (var id in EntryIDCollection.Split(','))
            {
                if (ns.GetItemFromID(id) is MailItem)
                {
                    Console.WriteLine(id + " is a mail item");
                }
            }

            Console.WriteLine("New mail thread Ended");
        }
    }
}

Thread.Sleep(5000); 期间,前景保持快乐且反应迅速。在调用下面的Console.WriteLine 时,原来的app_NewMailEx 事件处理程序早已返回。

但是,如果我在该行设置断点,或者以其他方式锁定我的应用程序以执行一些密集的任务 - 即使事件没有被重新触发,outlooks 在此期间仍然没有响应。

如果我在消息到达时删除事件处理程序,并在完成bg_DoWork 后重新添加它,那么它会缓解问题 - 但这意味着如果消息在这两次到达之间会丢失。

为什么会这样?在这种情况下,我怎样才能阻止 Outlook 变得反应迟钝?

【问题讨论】:

    标签: c# outlook office-interop


    【解决方案1】:

    这是一个命令行应用程序,它不运行 COM 使用的 Windows 消息泵。 你在 GUI 应用程序中使用过同样的问题吗?

    【讨论】:

    • 是的。命令行应用程序只是作为测试用例放在一起。我们正在开发的 WPF 应用程序也有同样的问题。
    • 你的代码是什么?您是否也在使用辅助线程/后台工作人员?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-05
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    • 1970-01-01
    相关资源
    最近更新 更多