我试着理解如果使用
await Task.Run(async () => MethodName())在MVC 5中,可以释放长时间运行的IO操作的线程,同时并行地继续执行其他代码任务。
我知道,简单地使用“等待MethodName()”将释放线程,但它不会移动到执行的代码单元MethodName()的下一行。(如果我错了,请纠正我)。
我希望能够在异步操作执行时释放线程,并并行执行其他代码。我想使用它来并行地对不同的数据源进行多次调用。这是“等待Task.Run(异步() => MethodName()”)实现的吗?
发布于 2015-03-11 21:56:26
不,别那么做。
相反,不要等待直到你不得不这样做。所以不要做
await MethodName();
DoSomeOtherWork();做
Task yourTask = MethodName();
DoSomeOtherWork();
await yourTask;这使得后台IO工作和DoSomeOtherWork()同时进行,而不需要绑定线程。
如果要执行多个IO任务,则可以将它们与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;这使得所有3项任务都可以同时进行,而不需要绑定任何线程。
发布于 2015-03-11 21:58:51
您可以将结果任务存储在某个变量中,并在稍后等待它。Ie:
var task = LongRunningMethodAsync();
SomeOtherWork();
SomeWorkOtherThanBefore();
awai task;您还可以存储许多方法的结果任务,并等待所有这些任务:
var tasks = new Task[] {
FirstMethodAsync(),
SecondMethodAsync(),
ThirdMethodAsync()
};
await Task.WhenAll(tasks);https://stackoverflow.com/questions/28998046
复制相似问题