我正在学习使用.NET 4.5的async/await构造。我正在开发一个RESTful Web API解决方案。我正在思考如何处理CPU-bound操作 - 是1)从当前线程同步调用,还是2)使用
让我们参考这个页面上的示例:
我阅读了Cleary先生的几篇文章,得到了一些混合的建议。在这篇文章中,他建议同步调用CPU密集型任务,以避免使用
Task.Run()
?让我们参考这个页面上的示例:
async Task<int> AccessTheWebAsync()
{
// You need to add a reference to System.Net.Http to declare client.
HttpClient client = new HttpClient();
// GetStringAsync returns a Task<string>. That means that when you await the
// task you'll get a string (urlContents).
Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");
// You can do work here that doesn't rely on the string from GetStringAsync.
DoCPUBoundWork();
// The await operator suspends AccessTheWebAsync.
// - AccessTheWebAsync can't continue until getStringTask is complete.
// - Meanwhile, control returns to the caller of AccessTheWebAsync.
// - Control resumes here when getStringTask is complete.
// - The await operator then retrieves the string result from getStringTask.
string urlContents = await getStringTask;
// The return statement specifies an integer result.
// Any methods that are awaiting AccessTheWebAsync retrieve the length value.
return urlContents.Length;
}
假设DoCPUBoundWork()
完全绑定于CPU,并且没有任何IO操作,那么从当前线程中调用它是否是最佳实践?
还是更好的方法是采用以下方式?
await Task.Run(() => DoCPUBoundWork()).ConfigureAwait(false);
我阅读了Cleary先生的几篇文章,得到了一些混合的建议。在这篇文章中,他建议同步调用CPU密集型任务,以避免使用
async/await/Task.Run()
带来的不必要开销。然而,在这篇文章中,他建议对于CPU密集型操作使用Task.Run()
,但没有提及任何特殊情况。我相信我应该错过了一些明显的东西。希望能够得到一些澄清。