首页 > 解决方案 > 尝试打开 Outlook 电子邮件时出现 WPF 任务/线程问题

问题描述

我有一个 WPF 应用程序,其中有一部分用户基本上填写类似 Outlook 的表单,然后用适当的信息填充 Outlook 电子邮件。问题是,当这封电子邮件打开时,代码执行会停止,直到电子邮件被发送或关闭。

我试图将它放在一个新线程上,但我在各个地方遇到了各种各样的问题,以使其工作。电子邮件表单的“正文”是一个富文本框,需要在将其放入 Outlook 电子邮件之前对其进行格式化,以使其正确显示。

从我读到的剪贴板调用必须放在他们自己的 STA 线程上,但在完成之前它会返回 null。

我怎样才能让它正常工作?基本上我想要的只是让 Outlook 电子邮件项位于其自己的线程上,这样它就不会在主线程打开时阻止其执行。

private async Task CreateEmail()
{

    try
   {
       //create an outlook object
       await Task.Run(() =>
     {
        MyOutlook.Application oApp = new MyOutlook.Application();

  //we need to check the to strings of that various items and join them together
        var toStrings = emailForm.ToMain;
        toStrings += String.IsNullOrEmpty(emailForm.ToRM) ? "" : ";" + emailForm.ToRM;
         toStrings += String.IsNullOrEmpty(emailForm.ToSM) ? "" : ";" + emailForm.ToSM;

         MyOutlook.MailItem oMailItem = (MyOutlook.MailItem)oApp.CreateItem(MyOutlook.OlItemType.olMailItem);
          oMailItem.To = toStrings;
          oMailItem.CC = emailForm.CC;
          oMailItem.BCC = emailForm.BCC;
          oMailItem.Subject = emailForm.Subject;
          oMailItem.RTFBody = GetRTBText();
          oMailItem.Display(true);
       });

      }
      catch(Exception ex)
     {
     ErrorWindow errWin = new ErrorWindow("There was an error creating the Outlook Email! Error: " + ex.Message);
     errWin.Show();
   }             
}

private byte[] GetRTBText() 
{

    byte[] RTFArr = null;
    //need to create a new STA Thread for the clipboard
    Thread thread = new Thread(() => Clipboard.Clear());

    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    thread.Join();
    this.Dispatcher.Invoke(() =>
    {
        RTBBody.SelectAll();
        RTBBody.Copy();                
    });
        Thread thread2 = new Thread(() => RTFArr = Encoding.UTF8.GetBytes  (Clipboard.GetText(TextDataFormat.Rtf)));
        thread2.SetApartmentState(ApartmentState.STA);
        thread2.Start();
        thread.Join();

    return RTFArr;
}

标签: c#wpfmultithreadingoutlook

解决方案


不要调用 Display(true) - 这将以模态方式显示消息。调用显示(假)。


推荐阅读