Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get returned value without await opeartor

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?

like image 847
Pandi Avatar asked Dec 05 '17 07:12

Pandi


3 Answers

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();
like image 54
lucky Avatar answered Oct 05 '22 16:10

lucky


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()

like image 38
MistyK Avatar answered Oct 05 '22 18:10

MistyK


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

like image 40
Titian Cernicova-Dragomir Avatar answered Oct 05 '22 17:10

Titian Cernicova-Dragomir