Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save normanlmfung/48a200ae57c2fd3dbd25f4c6bd027697 to your computer and use it in GitHub Desktop.
Save normanlmfung/48a200ae57c2fd3dbd25f4c6bd027697 to your computer and use it in GitHub Desktop.
csharp_eventdelegates
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public delegate void MessageArrivedHandler(string message);
class Publisher
{
private event MessageArrivedHandler _messageArrived = delegate {};
public event MessageArrivedHandler MessageArrived {
add {
_messageArrived += value;
}
remove {
_messageArrived -= value;
}
}
public void RaiseEvent(string message)
{
// So instead of 'Invoke', you can use 'GetInvocationList' and wrap each invocation with try-catch
// _messageArrived?.Invoke(message);
Delegate[] handlers = _messageArrived.GetInvocationList();
foreach (Delegate handler in handlers)
{
try
{
handler.DynamicInvoke(message);
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
}
record Subscriber(string Name)
{
public string SubscriberName { get; set; } = Name;
public void Subscribe(Publisher pub)
{
pub.MessageArrived += HandleEvent;
}
public void HandleEvent(string message)
{
Console.WriteLine($"Event handled by subscriber '{SubscriberName}': {message}");
}
}
static void Main(string[] args)
{
Publisher pub = new Publisher();
Subscriber sub1 = new Subscriber("sub1");
Subscriber sub2 = new Subscriber("sub2");
sub1.Subscribe(pub);
sub2.Subscribe(pub);
pub.RaiseEvent("Hello world.");
Console.WriteLine("Done!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment