Passa ai contenuti principali

Post

Visualizzazione dei post da aprile, 2017

C# Unicast Event: ensure an event has only one subscriber with the use of GetInvocationList

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. 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) { ClassThatFiresEv