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?
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();
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()
You have one of two options:
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
;
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With