C# async and sync switch

Use Task.FromResult() and Task.Run() when changing a normal method to async function.

Use (Task).GetAwaiter().GetResult() to get the result from an async method in a normal function.

    static async void Main(string[] args)
    {
        int a = await ResultZeroAsync();
        int b = ResultNumberAsync().GetAwaiter().GetResult();
    }

    static async Task<int> ResultZeroAsync()
    {
        return await Task.FromResult(0);
    }

    static async Task<int> ResultNumberAsync()
    {
        return await Task.Run(() => ResultZero());
    }

    static int ResultZero() => 0;

Leave a Comment

Your email address will not be published.