Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Event invocation list filtering

Tags:

c#

events

I have one event in C#. There are five subscribers for that. All the subscribers are different classes. But while raising the event i want that not all the subscriber/handler should be notified to handle this event. I should have some filtering mechanism and then only remaining subscribers should be notified. What could be the best way to achieve this?

like image 918
kamal nayan Avatar asked Oct 06 '22 02:10

kamal nayan


2 Answers

If you want to do it with your existing even then just iterate through the invocation list on the event.

var list = localHandler.GetInvocationList();
foreach (EventHandler<T> item in list)
{
    if(((ICanDoThing)item.Target).CanDoThing)
    {
        item(this, someArgs);
    }
 }

Now, you can see I've cast item.Target to a type of ICanDoThing, which is an interface I've just made up that exposes a method "CanDoThing". This allows you to query the object for whether it supports your particular need.

You should probably question whether you should use an event anyway for this, but the above will allow you to do so.

like image 193
Ian Avatar answered Oct 08 '22 16:10

Ian


You could use the observer pattern, described here: http://www.dofactory.com/Patterns/PatternObserver.aspx and implement your logic in the update method of the observer.

like image 27
NickD Avatar answered Oct 08 '22 16:10

NickD