【问题标题】:Why does SendMailAsync cause asp.net to wait, while Task.Delay doesn't?为什么 SendMailAsync 会导致 asp.net 等待,而 Task.Delay 不会?
【发布时间】:2017-07-30 15:20:38
【问题描述】:

我在 asp.net WebApi 操作中添加了以下行(原样,因此您也可以尝试):

new SmtpClient { DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory}.SendMailAsync("a@test.com", "b@test.com", "s", "b");

它导致操作等待几秒钟,直到抛出 An asynchronous module or handler completed while an asynchronous operation was still pending. 的 500 错误,显然 asp.net 检测到有一个异步任务正在运行。

当我添加时

Task.Delay(10000);

动作立即完成。为什么asp.net这里没有检测到有异步任务在运行?

【问题讨论】:

    标签: c# asp.net asynchronous


    【解决方案1】:

    SmtpClient.SendAsync 具有 HostProtectionAttributeExternalThreading 标志。这表明 ASP.NET 将涉及新线程,因此 ASP.NET 开始对这些等待完成的操作进行计数。

    如果您需要在 WebForms 中使用异步方法,您应该使用 RegisterAsyncTask 方法。

    【讨论】:

    • 谢谢。如果我想调用 SendMailAsync 但我不希望 WebApi 操作等到发送电子邮件,我会这样做吗?我也不想通过调用 Task.Run 来占用线程。
    • 你可以看看像stackoverflow.com/questions/36335345/web-api-fire-and-forget这样的帖子,Fire and forget 在网络上不是一个好的推荐。如果需要,WebServer 可以终止您的进程。
    猜你喜欢
    • 2016-04-18
    • 2021-12-17
    • 2016-11-18
    • 1970-01-01
    • 2016-10-20
    • 2014-01-28
    • 2019-08-22
    • 2012-07-11
    • 2020-01-23
    相关资源
    最近更新 更多