首页 > 解决方案 > 在任务未观察到的异常上模拟 ASP.NET 应用程序中的进程终止

问题描述

当从应用程序中抛出未观察到的任务异常时,我正在阅读以下文章ThrowUnobservedTaskExceptions来检查设置的行为。ThrowUnobservedTaskExceptions

我能够在控制台应用程序中使用以下设置来模拟应用程序/进程崩溃:

<ThrowUnobservedTaskExceptions enabled="true"/>

这是控制台应用程序代码:

程序.cs:

using System;
using System.Threading;
using System.Collections.Generic;
using System.Threading.Tasks;

//Use the following config settings to enable the throwing of unobserved exceptions.
//    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
//    <ThrowUnobservedTaskExceptions enabled="true"/>

public class Example
{
    static void Main()
    {
        Task.Run(() => { throw new InvalidOperationException("test"); });
        while (true)
        {
            Thread.Sleep(100);
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }
}

应用程序配置:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
    </startup>
    <runtime>
        <ThrowUnobservedTaskExceptions enabled="true"/>
    </runtime>
</configuration>

在运行上面的代码时,我可以看到正确的行为,ThrowUnobservedTaskExceptions即为未观察到的任务异常终止进程。运行与文档匹配的应用程序后,我能够获得以下屏幕。

在此处输入图像描述

我面临的问题是模拟 ASP.NET 应用程序中的确切行为。我有一个运行 targetFramework="4.8" 的 ASP.NET 应用程序。我无法在我的 ASP.NET 应用程序中模拟相同的行为,即进程/应用程序应该在面临未观察到的任务异常时被终止<ThrowUnobservedTaskExceptions enabled="true"/>设置。

这是应用程序控制器中的简单 API 代码:

[Route("api/ping"), HttpGet]
public IHttpActionResult TestPing()
{
    Task.Run(() => { throw new InvalidOperationException("test"); });
    while (true)
    {
        Thread.Sleep(100);
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
    return Ok("Pong");
}

这是确认我<ThrowUnobservedTaskExceptions enabled="true"/>在该应用程序的 Web 配置中使用设置的屏幕截图:

在此处输入图像描述

当我在浏览器中运行上述端点时: https://localhost:44364/api/ping 我不再看到 ASP.NET 进程被杀死。

无论我保持ThrowUnobservedTaskExceptions为真还是假,我的 ASP.NET 应用程序对于未观察到的任务异常都没有变化。我已经在发布模式下运行代码。System.Threading.Tasks.TaskScheduler.UnobservedTaskException在我的 ASP.NET 应用程序启动中没有附加处理程序。我还可以通过调用 API 来确认该public IHttpActionResult TestPing()方法正在被命中,并且证明 https://localhost:44364/api/ping 正处于加载状态,因为while (true)在该代码中但进程没有崩溃。

您能否分享一下为什么 ASP.NET 应用程序的上述行为与用于ThrowUnobservedTaskExceptions设置的控制台应用程序不同?

我的目标是模拟 ASP.NET 应用程序因未观察到的任务异常而崩溃。你能分享一段示例代码来实现我的目标吗?

标签: c#asp.netasynchronousasync-awaittask-parallel-library

解决方案


推荐阅读