how to raise event in all the object of my class?

795 Views Asked by At

I have C# class for which I am creating multiple objects for that class.

Now, I have one event for which all the objects of that class needs perform operation(In other words, I need to call specific function of all the object for that event).

The event is external to class.

Event is caused when I receive data from some external input in other class B or class C and I have to send that data to all the object of class A using method or event.

I need to raise event from multiple class B/C/D in class A.

1

There are 1 best solutions below

2
Ian Mercer On

A modern, clean way to handle this would be to use Reactive Extensions.

Suppose your event argument is of type EArg.

Place a static Subject<EArg> in your class A.

private static readonly Subject<EArg> subject = new Subject<EArg>();

Each instance of A can observe this IObservable<T> and act on it.

public ClassA()    // Constructor
{
   subject.Subscribe(HandleEvent);
}

private void HandleEvent(EArg arg)
{
   // ... 
}

When any external class calls (perhaps via a static method on class A) the OnNext method, all of the instances of class A can respond to it.

public static void RaiseEvent(EArg arg)
{
   subject.OnNext(arg);
}

Essentially you are looking for a pub-sub mechanism and Reactive Extensions is the cleanest way to achieve that.

NB, don't expose the Subject externally, see for example Why are Subjects not recommended in .NET Reactive Extensions?