我正在寻找有关调用多个异步方法的最佳实践,其中每个下一个方法都依赖于之前一个方法返回的值。
我正在尝试两种方法
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;
});
}
只是想了解最好的方法,因为我对异步编程有点陌生。
提前致谢!
强尼