AsyncEx icon indicating copy to clipboard operation
AsyncEx copied to clipboard

AsyncContext holds exceptions until all tasks complete.

Open DeathByNukes opened this issue 2 years ago • 0 comments

Hello,

I was trying to use AsyncContext to replace System.Windows.Threading.Dispatcher but ran into a problem: after an exception was thrown, the program would wait forever instead of exiting. It seems to be because the background async void loops were now allowed to continue running indefinitely even while the main thread body was terminated.

It seems strange that a program should continue running after an exception, so this seems to be a bug or undesirable default behavior. (The reverse situation where an async void function throws an exception seems to work correctly.)

Here is a reproduction of the problem:

// Dependencies: .NET 7, Nito.AsyncEx.Context 5.1.2
using Nito.AsyncEx;

namespace TestNet7;

internal class Program
{
	static int Main(string[] args)
		=> AsyncContext.Run(() => AsyncMain(args));

	static async Task<int> AsyncMain(string[] args)
	{
		_ = args;
		//throw new Exception("A");
		Console.WriteLine("A");
		await Task.Delay(TimeSpan.FromMilliseconds(1));
		//throw new Exception("B");
		Console.WriteLine("B");
		ScheduleC();
		throw new Exception("D");
		// Expected: Program immediately crashes.
		// Actual: Program waits 1 second to crash.
		return 0;
	}
	static async void ScheduleC()
	{
		//for (;;) // With this, the program can never crash!
		{
			await Task.Delay(TimeSpan.FromSeconds(1));
			//throw new Exception("C");
			Console.WriteLine("C");
		}
	}
}

Thank you.

DeathByNukes avatar Jul 30 '23 17:07 DeathByNukes