Created
March 28, 2024 05:01
-
-
Save normanlmfung/48a200ae57c2fd3dbd25f4c6bd027697 to your computer and use it in GitHub Desktop.
csharp_eventdelegates
This file contains hidden or 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.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