Tasks and Thread Scheduling in Asp.Net

拟墨画扇 提交于 2019-12-24 07:05:51

问题


In a Asp.Net Web page button click I have below code

//Code is running on Asp.Net worker Thread
var httpClient = new HttpClient();
var task = httpClient.GetAsync("/someapiCall");  //Creates a new thread and executed on it
task.Wait();

Now when I call task.Wait what will happen to the worker thread?

  1. Will it be in suspended state waiting for the httpClient call to complete?
  2. Will it be returned to thread pool and be available to process other requests?

Is there any difference between the above code and the below

var httpClient = new HttpClient();
var task = httpClient.GetAsync("/someapiCall");  //Creates a new thread and executed on it
ManualResetEvent mre = new ManualResetEvent(false);
task.ContinueWith((t) => { mre.Set(); });
mre.WaitOne();

回答1:


Your thread will be blocked synchronously waiting for the operation to complete in both cases. It will not go back to the ThreadPool.

There's no difference if you're blocking explicitly by using Wait or implicitly by waiting on a ManualResetEvent that would be set after the asynchronous operation completes.

Blocking synchronously on an async operation can lead to deadlocks in UI environments (and other cases where there's a SynchronizationContext, i.e. ASP.Net)

To not block that thread you should be using async-await:

await new HttpClient().GetAsync("/someapiCall");


来源:https://stackoverflow.com/questions/27559215/tasks-and-thread-scheduling-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!