Regarding: AsyncContextThread
https://github.com/StephenCleary/AsyncEx/wiki/AsyncContext
https://github.com/StephenCleary/AsyncEx/blob/master/src/Nito.AsyncEx.Context/AsyncContextThread.cs
It's not really covered how to handle catching exceptions that occur when the thread is started.
public partial class MyService : ServiceBase
{
private readonly AsyncContextThread _thread = new AsyncContextThread();
private readonly CancellationTokenSource _cts = new CancellationTokenSource();
public MyService()
{
InitializeComponent();
}
public void Start()
{
OnStart(null);
}
protected override void OnStart(string[] args)
{
try
{
_thread.Factory.Run(StartAsync);
}
catch (Exception ex)
{
// Exception?
}
}
private async Task StartAsync()
{
throw new Exception("things went wrong");
}
protected override void OnStop()
{
if (!_cts.IsCancellationRequested)
_cts.Cancel();
_thread.JoinAsync().GetAwaiter().GetResult();
}
}
I don't seem to catch anything in the catch{}
block, in addition I tried adding these to my Program.cs (main entry point).
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
However neither of the event handler methods are triggered in the above code.
Q) How do you handle exceptions correctly in this situation?
As a side note, I'm fairly sure that using AsyncContext
previously and debugging in Visual Studio did catch the exception, so I'm not sure if there's some sync. context I'm missing, when trying to add a handler for exceptions.
EDIT
I know I can try/catch
within the StartAsync
method, but the point I'm getting at is being able to catch any unhandled Exceptions and make sure I can log them.