调用相互依赖的多个异步方法

调用相互依赖的多个异步方法

问题描述:

我正在寻找有关调用多个异步方法的最佳实践,其中每个下一个方法都依赖于之前一个方法返回的值.

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

我正在尝试2种方法

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.

预先感谢!

Johny

我正在寻找有关调用多个异步方法的最佳实践,其中每个下一个方法都依赖于先前一个方法返回的值.

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

通过查看同步等效项,可以回答很多异步问题.如果所有方法都是 synchronous ,并且每个方法都取决于先前方法的结果,那看起来如何?

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

那么异步等效项将是:

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

P.S.为了将来参考,请勿插入StartNewTask.Run作为异步代码的通用占位符;因为他们有非常特定的用例,所以他们只是使问题感到困惑.使用await Task.Delay代替;这是异步世界的Thread.Sleep.

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.