是否有可能调用非异步方法的awaitable的方法? [英] Is it possible to call an awaitable method in a non async method?

查看:100
本文介绍了是否有可能调用非异步方法的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;
}

这篇关于是否有可能调用非异步方法的awaitable的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆