任务和线程在Asp.Net调度 [英] Tasks and Thread Scheduling in Asp.Net
问题描述
在一个Asp.Net网页按钮,点击下面我有code
// $ C $,C是Asp.Net工作线程运行
VAR的HttpClient =新的HttpClient();
VAR任务= httpClient.GetAsync(/ someapiCall); //创建一个新的线程,并在其上执行
task.Wait();
现在,当我打电话task.Wait会发生什么工作线程?
- 会不会是挂起状态,等待HttpClient的调用完成?
- 它会被返回到线程池,可用于处理其他请求?
有没有之间的上述code和下面的
有什么区别 VAR的HttpClient =新的HttpClient();
VAR任务= httpClient.GetAsync(/ someapiCall); //创建一个新的线程,并在其上执行
ManualResetEvent的MRE =新的ManualResetEvent(假);
task.ContinueWith((吨)=> {mre.Set();});
mre.WaitOne();
您的线程将被阻塞同步等待操作完成在这两种情况下。它不会返回到线程池
。
目前使用等待
或隐含的由等待一个<$没有区别,如果你阻止的明确的C $ C>的ManualResetEvent 将异步操作后设置完成。
在一个异步
操作阻止同步可能导致用户界面环境(和其他情况下的死锁,其中有一个的SynchronizationContext
,如ASP.Net)
要不会阻止你应该使用线程异步等待
:
等待新的HttpClient()GetAsync(/ someapiCall)。
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();
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");
这篇关于任务和线程在Asp.Net调度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!