Skip to content

Instantly share code, notes, and snippets.

@CodingOctocat
Created April 13, 2025 11:29
Show Gist options
  • Save CodingOctocat/b70b059c0015555c45dc13efa710b4e0 to your computer and use it in GitHub Desktop.
Save CodingOctocat/b70b059c0015555c45dc13efa710b4e0 to your computer and use it in GitHub Desktop.
using System;
using System.Threading.Tasks;
/// <summary>
/// <see href="https://www.devleader.ca/2023/02/14/async-eventhandlers-a-simple-safety-net-to-the-rescue/">Async EventHandlers – A Simple Safety Net To The Rescue</see>
/// </summary>
public static class AsyncEventHandlers
{
public static EventHandler<TArgs> TryAsync<TArgs>(
Func<object?, TArgs, Task> callback,
Action<Exception> errorHandler) where TArgs : EventArgs
{
return TryAsync(callback, ex => {
errorHandler.Invoke(ex);
return Task.CompletedTask;
});
}
public static EventHandler<TArgs> TryAsync<TArgs>(
Func<object?, TArgs, Task> callback,
Func<Exception, Task> errorHandler) where TArgs : EventArgs
{
return new EventHandler<TArgs>(async (object? s, TArgs e) => {
try
{
await callback.Invoke(s, e);
}
catch (Exception ex)
{
await errorHandler.Invoke(ex);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment