问题
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?
- Will it be in suspended state waiting for the httpClient call to complete?
- 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