【问题标题】:Tasks and Thread Scheduling in Asp.NetAsp.Net 中的任务和线程调度
【发布时间】:2014-12-19 03:13:22
【问题描述】:

在 Asp.Net 网页按钮中单击我有以下代码

//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();

现在当我调用 task.Wait 时工作线程会发生什么?

  1. 会处于挂起状态等待 httpClient 调用完成吗?
  2. 是否会返回到线程池并可以处理其他请求?

上面的代码和下面的代码有什么区别

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();

【问题讨论】:

    标签: c# asp.net .net multithreading task-parallel-library


    【解决方案1】:

    在这两种情况下,您的线程将被同步阻塞,等待操作完成。它不会回到ThreadPool

    如果您通过使用Wait隐式 通过等待异步操作完成后设置的ManualResetEvent显式 阻止,没有区别。

    async 操作上同步阻塞可能会导致 UI 环境中的死锁(以及存在 SynchronizationContext 的其他情况,即 ASP.Net)

    为了不阻塞你应该使用async-await的线程:

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

    【讨论】:

    • 使用 await 意味着我必须使用异步页面处理程序对吗?否则响应会在异步任务完成之前返回浏览器。
    • @SriHarshaVelicheti 我相信是的。看看this
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 2021-02-09
    相关资源
    最近更新 更多