【发布时间】:2015-08-04 21:36:10
【问题描述】:
我对 .NET 4.5 的 async/await 结构感到很困惑。我正在开发一个 RESTful Web API 解决方案。我试图弄清楚如何处理受 CPU 限制的操作 - 1) 从当前线程同步调用它,或者 2) 使用 Task.Run()?
让我们使用来自page 的示例:
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);
我已经阅读了克利里先生的一些帖子,并且收到了一些混杂的建议。在这个post 中,他建议最好同步调用CPU 绑定的东西以避免async/await/Task.Run() 的不必要开销。但是,在这个post 中,他建议将Task.Run() 用于CPU 绑定操作,而无需提及任何异常情况。我确定我遗漏了一些明显的东西。希望得到一些澄清。
【问题讨论】:
-
DoIndependentWork 通常运行多长时间?
-
假设它需要足够长的时间在高负载下引起问题......
标签: c# asp.net .net async-await task-parallel-library