【发布时间】:2015-04-01 20:30:49
【问题描述】:
由于一些优化问题,我决定将控制器的操作方法重写为异步方法。它是一个多层应用程序,从那以后,我面临着架构问题,我想知道我将在下面展示的两种方法之间的主要区别是什么。假设我的同步方法是:
public virtual ActionResult Method()
{
SomeLogic.LargeOperation();
return View(...);
}
LargeOperation 做了很多工作。这是伪代码:
public void LargeOpertion() {
DatabaseManipulations1();
IndependentWork();
CallingToWebService1();
IndependentWork();
DatabaseManipulations2();
IndependentWork();
CallingToWebService2();
IndependentWork();
}
LargeOperations 中的每个方法本身都有几个方法,依此类推……问题是:我是否需要使它们全部异步并在几乎每个应用程序层中使用 await?
public virtual Task<ActionResult> Method()
{
await SomeLogic.LargeOperation();
return View(...);
}
public async Task LargeOpertion() {
await DatabaseManipulations1();
IndependentWork();
await CallingToWebService1();
IndependentWork();
await DatabaseManipulations2();
IndependentWork();
await CallingToWebService2();
IndependentWork();
}
或者我可以像这样在 LargeOperation 上使用任务:
public virtual Task<ActionResult> Method()
{
await Task.Run(() => SomeLogic.LargeOperation());
return View(...);
}
我们还假设 IndependentWork() 没有那么大。
【问题讨论】:
-
多长时间 /long/ 我们在谈分钟吗? 1秒?小时?
-
如果
LargeOperation是异步的,让它返回Task,否则使用Task.Run(() => SomeLogic.LargeOperation());。除此之外,我不明白你的问题。 -
假设CallingToWebService1中有一个操作可以持续2分钟左右,DatabaseManipulations1(), DatabaseManipulations2(), CallingToWebService2() 1分钟左右
-
LargeOperation 很复杂。它包含许多WebServiceCalls、数据库操作。我不知道我是应该在更深层使用 Task.Run 和 async/await(并等待它直到控制器层)还是只在控制器中使用 Task.Run。
-
Task.Run会影响性能,因为它只是为了将当前线程释放到线程池而跳入另一个线程轮询线程,从而付出代价却没有任何好处。如果你有很多异步 IO,那么你应该使用async-await来提高整体性能和响应能力,但不要异步超过同步。
标签: c# asp.net asynchronous async-await