问题
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