How to get returned value without await opeartor

吃可爱长大的小学妹 提交于 2020-07-02 09:47:14

问题


I need to get the returned value without await operator(in below sample I need to get the "hello world" in var y without await operator). Because one method is referred to a lot of places.But my requirement is that method is executed at asynchronously for particular operations. None other time it is enough to be executed as synchronously.

If I put await in all referred places that method needs to change as async and also referred methods need to change as async and await. Is there any possibility to get the returned value?

Please find below sample code snippet:

class Program
{
    static void Main(string[] args)
    {
        var x = getString();
    }

    public static async Task<string> getString()
    {
        var y = await GetString2();
        return y;
    }

    public static async Task<string> GetString2()
    {
        return "hello world";
    }

}

Here is there any possibility to get "hello world" string in var y without await operator?


回答1:


Are you looking for something like that;

var str = GetString2().Result;

Result blocks the calling thread until the asynchronous operation is complete; it is equivalent the Wait method. await has asynchronous wait for the task completion.

Also, as @Sir Rufo and @MistyK described, you will get AggregateException on a possible exception, so it would be better to use GetAwaiter like this;

var str = GetString2().GetAwaiter().GetResult();



回答2:


I wouldn't use Result because If error is thrown, you'll get AggregateException. It's better to do this:

var str = GetString2().GetAwaiter().GetResult()




回答3:


You have one of two options:

  1. Either use the Result property of the task. This has the downside that it can block the message pump and cause problems. In a console app this might work, but you need to test.

    GetString2().Result;

  2. Use the ContinueWith method to pass an action to perform when the task is complete. The disadvantage being you will not have access to the data immediately, and the calling function will return.

    GetString2().ContinueWith(result => Console.WriteLine(result));



来源:https://stackoverflow.com/questions/47648245/how-to-get-returned-value-without-await-opeartor

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