是否有可能调用非异步方法的awaitable的方法?

是否有可能调用非异步方法的awaitable的方法?

问题描述:

在一个窗口在C#/ XAML 8应用程序,我有时想调用从非异步方法的awaitable方法。

In a windows 8 application in C#/XAML, I sometimes want to call an awaitable method from a non asynchronous method.

其实是正确的,以取代这样的:

Actually is it correct to replace this :

  public async Task<string> MyCallingMethod()
  {
      string result = await myMethodAsync();
      return result;
  }

本:

   public string MyCallingMethod()
   {
       Task.Run(async () => {
            string result = await myMethodAsync();
            return result;
             });
   }

我的优势在于我可以使用MyCallingMethod没有的await但是这是正确的?
这可能是一个优势,如果我想通过对MyCallingMethod ref参数,因为它是不可能在异步方法ref参数。

The advantage for me is that I can use MyCallingMethod without await but is this correct? This can be an advantage if I want to pass a ref parameter for MyCallingMethod since It is not possible to have ref parameters in an async method.

在非异步方法您可以异步启动任务,而不是等待结果:

In non-async method you can either start the Task asynchronously and not wait for the result:

public void MyCallingMethod()
{
    Task t = myMethodAsync();
}

也可以附加ContinueWith事件处理程序,这是在完成任务之后调用,

or you can attach ContinueWith event handler, which is called after finishing the Task,

public void MyCallingMethod()
{
    myMethodAsync().ContinueWith(
        result =>
        {
            // do stuff with the result
        });
}

或者你可以从任务同步的结果是:

or you can get the result from the Task synchronously:

public string MyCallingMethod()
{
    string result = myMethodAsync().Result;
    return result;
}