[英]Outlook interop causes outlook to stall *after* event handler has finished
我遇到一個問題,即如果我的應用程序正忙/無響應/為斷點暫停,即使我收到的郵件事件處理程序早已返回,它也會導致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
事件處理程序早已返回。
但是,如果我在那條線上斷點,或者以其他方式將我的應用程序鎖定為執行一些繁重的任務-在這段時間內,即使事件沒有被重新觸發,前景仍然沒有響應。
如果我在消息到達時刪除事件處理程序,並在完成bg_DoWork
之后再次添加它,那么它可以緩解問題-但這意味着如果消息在兩次之間到達則將丟失。
為什么會這樣? 在這種情況下,如何阻止Outlook變得毫無反應?
這是一個命令行應用程序,它不運行COM使用的Windows消息泵。 您是否在GUI應用程序中遇到相同的問題?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.