问题
I am trying to understand if using
await Task.Run(async () => MethodName())
in MVC 5 gives the benefits of freeing up the thread of a long running IO operation, while continuing with other code tasks in Parallel.
I know that simply using "await MethodName()" will free up the thread, but it will not move to the next line of code unit MethodName() is done executing. (Please correct me if I am wrong).
I'd like to be able to free up the thread while the async operation is executing, as well as execute other code in parallel. I'd like to use this in order to make multiple calls to different data sources in parallel. Is this what "await Task.Run(async () => MethodName())" achieves?
回答1:
No, don't do that.
Instead just don't await till you have to. So instead of doing
await MethodName();
DoSomeOtherWork();
do
Task yourTask = MethodName();
DoSomeOtherWork();
await yourTask;
This lets both the background IO work happen and your DoSomeOtherWork()
at the same time without tying up a thread.
If you have multiple IO tasks to perform you can group them all together with a Task.WhenAll
Task<DbOneResults> dbOne= GetDbOneRecords();
Task<DbTwoResults> dbTwo = GetDbTwoRecords();
Task<DbThreeResults> dbThree = GetDbThreeRecords();
//This line is not necessary, but if you wanted all 3 done before you
//started to process the results you would use this.
await Task.WhenAll(dbOne, dbTwo, dbThree);
//Use the results from the 3 tasks, its ok to await a 2nd time, it does not hurt anything.
DbOneResults dbOneResults = await dbOne;
DbTwoResults dbTwoResults = await dbTwo;
DbThreeResults dbThreeResults = await dbThree;
This lets all 3 tasks happen at once without tying up any threads.
回答2:
You can store the resulting task in some variable and await it later. Ie:
var task = LongRunningMethodAsync();
SomeOtherWork();
SomeWorkOtherThanBefore();
awai task;
You can also store resulting tasks of many methods and wait for all of them:
var tasks = new Task[] {
FirstMethodAsync(),
SecondMethodAsync(),
ThirdMethodAsync()
};
await Task.WhenAll(tasks);
来源:https://stackoverflow.com/questions/28998046/task-run-methodname-and-await-task-runasync-methodname