Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AsyncContext holds exceptions until all tasks complete. #279

Open
DeathByNukes opened this issue Jul 30, 2023 · 0 comments
Open

AsyncContext holds exceptions until all tasks complete. #279

DeathByNukes opened this issue Jul 30, 2023 · 0 comments

Comments

@DeathByNukes
Copy link

DeathByNukes commented Jul 30, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant