Events in c# are designed for multicasting: one publisher for many subscribers. Limiting the number of subscribers may seeem an anti-pattern but in some cases may come in handy.
Here is a simple implementation of an event that limits to one the number of subscribers.
The code for testing this class:
The Output is:
Anon 2
Here is a simple implementation of an event that limits to one the number of subscribers.
public class ClassThatFiresEvents
{
public Action _myAction;
public event Action MyUnicastEvent
{
add
{
if (_myAction != null)
{
var invList = _myAction.GetInvocationList();
foreach (var ev in invList)
{
_myAction -= (Action)ev;
}
}
_myAction += value;
}
remove
{
_myAction -= value;
}
}
public void TriggerFromOutside()
{
if (_myAction != null)
_myAction();
}
}
The code for testing this class:
static void Main(string[] args)
{
ClassThatFiresEvents c = new ConsoleApplication1.ClassThatFiresEvents();
c.MyUnicastEvent += Method1;
c.MyUnicastEvent += Method2;
c.MyUnicastEvent += () => { Console.WriteLine("Anon 1"); };
c.MyUnicastEvent += () => { Console.WriteLine("Anon 2"); };
c.TriggerFromOutside();
}
private static void Method1() { Console.WriteLine("Method1"); }
private static void Method2() { Console.WriteLine("Method2"); }
The Output is:
Anon 2
Commenti