Passa ai contenuti principali

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

Post popolari in questo blog

Log.Net: Conflitto Con CrystalReport per Visual Studio 2010

Situazione: Web Application Asp.Net 4.0, Utilizzo delle librerie di Crystal Report per VS2010. Il progetto web utilizza Log.Net, scaricato dal sito ufficiale. Un problema simile si verifica con applicazioni Windows Form. Problema: Le due librerie vanno in conflitto sia in fase di compilazione ( 1550854 - "Could not load file or assembly 'log4net' or one of its dependencies" Error when building Visual Studio 2010 solution utilizing the Crystal Reports .NET Runtime ), sia una volta installata sulla macchiana target (L'inizializzatore di tipo di 'CrystalDecisions.Shared.SharedUtils' ha generato un'eccezione. Impossibile caricare il file o l'assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304' o una delle relative dipendenze. La definizione di manifesto dell'assembly specificato non corrisponde al riferimento all'assembly.). Soluzione Spiegata: Il thread in cui ne parlano. A quanto ho ca...

Dotnetnuke non migrerà ad asp .NET MVC

Il grande capo di dnn Shawn Walker ha messo in chiaro che non tenteranno un porting di dnn verso asp .Net MVC, dotnetnuke resterà per sempre su web forms. La scelta è tanto saggia quanto obbligata. Esiste però un modo per estendere DNN o integrarlo con un'applicazione MVC? sembra di si, il completo tutorial in 3 parti direttamnte dai blog ufficiali delgi sviluppatori Dnn: parte1 parte2 parte3 Per completezza qui il famoso post di ScottGu sulla volontà di microsoft di tenere in piedi con uguali risorse sia asp.Net MVC sia WebForms.

Xamarin Forms Image: where to put images in projects (root directory in WindosPhone)

We have a PCL Xamarin.Forms project with some XAML. Images are project-specific so we put the image in the starting projec (i.e. Wp and Android) We want to define image name in the XAML so we use: x:Name="myImage"  Source="NavigationLeft.png" Android takes the "NavigationLeft.png" in the Resources/Drawable WindowsPhone takes the "NavigationLeft.png" on the root of the project. So Windows phone project get messed with resource images in the root folder. Is there a way to avoid this? No, there's not: in Windows Phone  we could place the image in an "Images" forder and reference it with "Images/NavigationLeft.png" in XAML, this would work. But in Android the Resource/drawable directory is a flat diretory and does allow subdirs. For now i prefixed share image with an x "xNavigationLeft". Sources: Android drawable does not allow subdirs For Wp using Xamarin.Forms we must put images on root dir