以下代码在 netcoreapp2.0 应用程序中运行时,似乎最终不会抛出UnobservedTaskException
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp3 {
class Program {
public static void Main(string[] args) {
TaskScheduler.UnobservedTaskException += (s, e) => {
/// Try to crash the application - we wanna nail unobserved exceptions dead.
/// Unfortunately, this code never seems to run.
Console.WriteLine("UnobservedTaskException thrown.");
throw e.Exception;
};
var t = Task.Run(() => {
throw new NotImplementedException();
});
while (!t.IsFaulted)
Thread.Sleep(1);
t = null;
Console.WriteLine("Task is faulted.");
GC.Collect();
GC.WaitForPendingFinalizers();
Console.ReadKey();
}
}
}
这是项目文件。我怎样才能让UnobservedTaskException
处理程序被解雇?
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.2</TargetFramework>
<LangVersion>7.3</LangVersion>
</PropertyGroup>
</Project>
在其他 stackoverflow 帖子中,我看到了在项目文件中使用以下代码段的建议,但它仅适用于 .net 框架 4.0+ 项目。如果有 .netcore 项目文件的等效文件,那可能就是我需要知道的。
<runtime>
<ThrowUnobservedTaskExceptions enabled="true"/>
</runtime>