【问题标题】:C# VSTO Call async method from other add-in, and await for responseC# VSTO 从其他加载项调用异步方法,并等待响应
【发布时间】:2018-04-08 23:47:22
【问题描述】:

我有一个正在运行的 Outlook 加载项,它有一个公开的异步函数,它返回一个

System.Threading.Tasks.Task<String> object.

当我从另一个应用程序调用此方法时,我得到以下异常:

System.__ComObject' does not contain a definition for 'GetAwaiter'

我的 Outlook 异步函数工作是:

  1. 发送和接收新电子邮件
  2. 如果有新邮件进来,则通过 ItemAdd 事件处理它们
  3. 如果处理完成,则创建它们的报告
  4. 将此报告返回给我的其他应用程序

我如何从宿主应用程序调用异步方法:

public static async void GetOutlookReport() 
{
    object addInName = "myOutlookAddIn";
    var outlookApplication = (Microsoft.Office.Interop.Outlook.Application)Marshal.GetActiveObject("Outlook.Application");
    Office.COMAddIn addIn = outlookApplication.COMAddIns.Item(ref addInName);
    if (addIn != null)
    {
        String Report = await addIn.Object.myAsyncOutlookFunction("parameter1"); //failes here
        //do whatever with report...
    }
}

方法在 Outlook 插件中的声明方式:

-我的 Ribbon.cs 类文件有以下内容:

[ComVisible(true)]
public interface IAddInUtilities
{
    System.Threading.Tasks.Task<String> myAsyncOutlookFunction(String Param1);
}

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class AddInUtilities : StandardOleMarshalObject,
IAddInUtilities
{
    public async System.Threading.Tasks.Task<String> myAsyncOutlookFunction(String Param1)
    {
        String x = await myAsyncOutlookFunctionDefined(Param1);
        return x;
    }
}

-myAsyncOutlookFunctionDefined 的实现:

public static async Task<String> myAsyncOutlookFunctionDefined(String Param1)
{
    try
    {
        //try to get all new emails in
        await CallSendAndReceive(); //function that simply calls NameSpace.SendAndReceive();

        //after SendAndReceive finished, the ItemAdd events should run (code not implemented yet)
        //after ItemAdd events have finished we create the report

        String Report = CreateReport(); //this function is irrelevant right now
        return Report;
    }
    catch(Exception ex)
    {
        return "";
    }
}

是否有可能从我的主机应用程序等到

  • Outlook 以 SendAndReceive 结束
  • 在收件箱文件夹中运行所有 ItemAdd 事件
  • 自己处理
  • 通过字符串形式将报告发送回主机应用程序?

我们的想法是,运行该函数最多 30 秒,如果它没有完成获取电子邮件并处理它们以创建报告,那么只返回一个空字符串。

如果我无法通过从其他应用程序(主机)调用异步函数获得响应,我将无法继续此开发。

注意:

只是为了好玩,我在 Outlook 加载项中添加了一个按钮,用于模拟相同的操作。当我单击该按钮时,我可以调用相同的 myAsyncOutlookFunction,但是,我不通过 Office.COMAddIn 对象调用它,而是直接调用它。它运行平稳,这意味着 System.Threading.Tasks.Task 对象具有正确的数据。

这种证明,通过暴露的类调用它是问题的根源......

【问题讨论】:

    标签: c# asynchronous outlook vsto outlook-addin


    【解决方案1】:

    缺少 GetAwaiter() 调用似乎表明正在运行调用代码的框架版本不支持 async/await。使用纯 TPL(不使用 async/await 关键字)测试调用方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-29
      • 2021-11-24
      • 2018-01-07
      • 2013-04-15
      • 2011-09-03
      • 1970-01-01
      • 2016-10-13
      • 1970-01-01
      相关资源
      最近更新 更多