Using a List<Action<T>> instead of an event can be a practical approach if you want more control over error handling and management of your event subscribers. With an event, if one of the subscribers throws an exception, it can potentially halt the invocation of remaining subscribers. By manually managing a list of delegates, you can handle each invocation separately and ensure that an exception in one subscriber doesn't affect others.
Here's how you might implement it using a List<Action<T>>:
public class ApiProvider<T>
{
private List<Action<T>> onReadyHandlers = new List<Action<T>>();
public T? Instance { get; private set; }
public void AddOnReadyHandler(Action<T> handler)
{
if (Instance != null)
handler(Instance);
lock (onReadyHandlers)
{
onReadyHandlers.Add(handler);
}
}
public void RemoveOnReadyHandler(Action<T> handler)
{
lock (onReadyHandlers)
{
onReadyHandlers.Remove(handler);
}
}
public void Register(T instance)
{
Instance = instance;
InvokeHandlers(instance);
}
private void InvokeHandlers(T instance)
{
List<Action<T>> handlersCopy;
lock (onReadyHandlers)
{
handlersCopy = new List<Action<T>>(onReadyHandlers);
}
foreach (var handler in handlersCopy)
{
try
{
handler(instance);
}
catch
{
// Optionally log the exception or take other actions.
}
}
}
}
Key Points:
-
List of Actions: Instead of using an event, we maintain a List<Action<T>> to store the handlers. This gives us more control over adding, removing, and invoking these handlers.
-
Synchronization: Access to the list is synchronized with lock to ensure thread safety when adding or removing handlers, or when making a copy of the handlers for invocation.
-
Exception Handling: Each handler is invoked in a try-catch block. This ensures that if one handler throws an exception, the others will still be executed.
-
Copy for Invocation: We create a copy of the handlers list before invoking them. This avoids potential modification of the list during iteration, which can lead to exceptions.
By handling the list of actions manually, you have the flexibility to manage event subscribers and handle errors in a way that best suits your application's needs.