Is it possible to call an awaitable method in a non async method? [duplicate]

社会主义新天地 提交于 2019-12-20 08:49:16

问题


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;
  }

by this :

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

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.


回答1:


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

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

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;
}



回答2:


You really shouldn't try to do something like that if you're on the UI thread, because that will mean you will block the thread. You should instead work around the ref parameter, for example by accepting a parameter of a simple class type, that contains the value you want to change.

Another reason why not to do this is that it still won't let you use ref parameters, because lambdas can't access ref parameters of the enclosing method.

But if you really want to do this (again, I really think you shouldn't), then you will need to get the result of the Task. Something like:

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


来源:https://stackoverflow.com/questions/12402681/is-it-possible-to-call-an-awaitable-method-in-a-non-async-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!