How to get return value without waiting for opeartor

I need to get the return value without waiting for the statement (in the following example I need to get "hello world"in var ywithout waiting for the statement). Because one method applies to many places. But my requirement is that the method runs asynchronously for certain operations. At no other time is this enough to execute as synchronously.

If I wait in all the mentioned places, this method should change, since async and also the mentioned methods should change as async and wait. Is there any way to get the return value?

The following is an example 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 the opportunity to get the string "hello world" in without waiting for the operator? var y

+4
3

- :

var str = GetString2().Result;

Result ; Wait. await .

, @Sir Rufo @MistyK, AggregateException , GetAwaiter :

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

Result, , AggregateException. :

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

+4

:

  • Result . , . , .

    GetString2().Result;

  • Use the method ContinueWithto pass the action to be performed when the task is completed. The disadvantage is that you will not have access to the data immediately and the calling function will return.

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

+2
source

Source: https://habr.com/ru/post/1690253/


All Articles