I have an async void
event handler that must stay “fire-and-forget”. Sadly, it contains logic that may throw an exception. I was thinking of putting the actual business logic inside an async Task
that is awaited inside the async void HandleMessageSafely()
method that only has the responsibility of catching and logging errors.
The HandleMessage
method may be overridden by subclasses of Example.MessageHandler
I’m not asking if this is good design (I assume it’s not), but if it is safe, and does not interfere with my “fire and forget” requirements. To me this solution seems pretty straight forward, but I didn’t find any similar examples on the net and I am afraid that I am missing something. Bonus points for a “nice” solution.
using System;
using System.Threading.Tasks;
namespace Example.MessageHandler;
public class MessageHandler<TMessage>
{
protected async Task HandleMessage(TMessage mEvent)
{
// some async logic that needs await but may throw an exception
throw new ApplicationException();
}
public async void HandleMessageSafely(TMessage message)
{
try
{
await HandleMessage(message);
}
catch (Exception ex)
{
Console.WriteLine("Uncaught exception");
}
}
}