The following code, when run in a netcoreapp2.0 application, doesn't seem to end up throwing the 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();
}
}
}
Here's the project file. How can I get the UnobservedTaskException
handler to be fired?
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.2</TargetFramework>
<LangVersion>7.3</LangVersion>
</PropertyGroup>
</Project>
In other stackoverflow posts, I've seen advice to use the following snippet in the project file, but it only works for .net framework 4.0+ projects. If there's an equivalent for the .netcore project file, that might be what I need to know.
<runtime>
<ThrowUnobservedTaskExceptions enabled="true"/>
</runtime>