Call multiple async methods that rely on each other

我怕爱的太早我们不能终老 提交于 2019-12-19 04:55:34

问题


I'm looking for best practice around calling multiple async methods where each next method relies on the values returned from one before.

I'm experimenting with 2 approaches

1) https://dotnetfiddle.net/waPL9L

public async void Main()
    {       
        var T1 = await Sum(2,5);
        var T2 = await Sum(T1, 7);
        var T3 = await Sum(T2, 7);      

        Console.WriteLine(T3);
    }

    public async Task<int> Sum(int num1, int num2){
        return await Task.Run(() => {
            // for some reason if i use Sleep... I don't see any results at all...
            //Thread.Sleep(2000);
            return num1 + num2;
        });
    }

2) https://dotnetfiddle.net/1xycWH

public async void Main()
    {
        var T1 = Sum(2,5);
        var T2 = Sum(T1.Result, 7);
        var T3 = Sum(T2.Result, 7);

        //var myVar = T3.Result;

        var listOfTasks = new List<Task>{T1,T2,T3};

        await Task.WhenAll(listOfTasks);

        Console.Write(T3.Result);
    }

    public async Task<int> Sum(int num1, int num2){
        return await Task.Run(() => {
            Thread.Sleep(1000);
            return num1 + num2;
        });
    }

Just trying to understand best approach as I'm kind of new to async programming.

Thanks in Advance!

Johny


回答1:


I'm looking for best practice around calling multiple async methods where each next method relies on the values returned from one before.

A lot of asynchronous questions can be answered by looking at the synchronous equivalent. If all the methods are synchronous and each method depends on the results of previous methods, how would that look?

var T1 = Sum(2,5);
var T2 = Sum(T1, 7);
var T3 = Sum(T2, 7);

Then the asynchronous equivalent would be:

var T1 = await SumAsync(2,5);
var T2 = await SumAsync(T1, 7);
var T3 = await SumAsync(T2, 7);

P.S. For future reference, do not insert StartNew or Task.Run as generic placeholders for asynchronous code; they just confuse the issue since they have very specific use cases. Use await Task.Delay instead; it's the Thread.Sleep of the async world.



来源:https://stackoverflow.com/questions/54798456/call-multiple-async-methods-that-rely-on-each-other

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