关于从异步方法同步调用CPU绑定方法的困惑

Zoo*_*oom 8 .net c# asp.net task-parallel-library async-await

我正熟悉.NET 4.5的异步/等待构造.我正在研究RESTful Web API解决方案.我试图找出如何处理CPU绑定操作 - 1)从当前线程同步调用它,或2)使用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;
}
Run Code Online (Sandbox Code Playgroud)

在这里,我们假设DoCPUBoundWork()严格受CPU约束,并且不涉及任何类型的IO.

如图所示,从当前线程调用它是最佳做法吗?

或者更好的是拥有以下内容?

await Task.Run(() => DoCPUBoundWork()).ConfigureAwait(false);
Run Code Online (Sandbox Code Playgroud)

我已经阅读了Cleary先生的一些帖子,并得到了一些不同的建议.在这篇文章中,他建议最好同步调用CPU绑定的东西,以避免不必要的开销async/await/Task.Run().但是,在这篇文章中,他建议使用Task.Run()CPU绑定操作而不提及任何异常情况.我确定我错过了一些明显的东西.希望得到一些澄清.

Yuv*_*kov 6

如图所示,从当前线程调用它是最佳做法吗?

如果您正在进行异步操作时当前线程是空闲的,为什么要使用不同的线程?是什么让这个线程比你已经使用的线程更好?

关于DoIndependentWork实际在做什么的问题浮现在脑海中.如果在HTTP请求完成之前完成它是至关重要的,我会同步调用它.如果在HTTP请求完成之前完成工作并不重要,那么我会寻找完全不同的解决方案.Task.Run在ASP.NET中使用是危险的.

请记住,ASP.NET中的延续在任意线程池线程上运行.

  • @Andreas你是对的,万一这是WPF,我会提出不同的建议.但这是ASP.NET,这是不同的. (2认同)
  • @Zoomzoom在ASP.NET中,你甚至不应该使用`Task.Run`.它不会注册工作,IIS可能会在应用程序执行时回收它.在基于UI的应用程序中使用`Task.Run`更有意义,我假设这是Stephan所指的. (2认同)