Created
April 13, 2025 11:29
-
-
Save CodingOctocat/b70b059c0015555c45dc13efa710b4e0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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