Tuesday, November 22, 2016

Pipelining events in C# .Net

The concept of Events is a good technique in .Net for establishing publisher-subscriber mechanism. When we work on .Net projects there would be situations where we have to raise an event when some of our dependency raise an event.

For example, our class A holds object of class B. A receive event BE1 from class B and fires AE1. A Simple event relay mechanism.

How that can be done inside class A?

Receive event and fires next event

class A
{
    B bObject=new B();
    public A()
    {
        InitializeB();
    }
 
    private void InitializeB()
    {
        bObject.BE1 += BObject_BE1;
    }
 
    private void BObject_BE1(object sender, EventArgs e)
    {
        this.OnAE1(e);
    }
 
    public event EventHandler AE1;
    protected virtual void OnAE1(EventArgs args)
    {
        if (AE1 != null)
        {
            AE1(this, args);
        }
    }
}
Below is the code for class B. It uses a simple timer to fire events.
class B
 {
     public event EventHandler BE1;
     protected virtual void OnBE1(EventArgs args)
     {
         if (BE1 != null)
         {
             BE1(this, args);
         }
     }
 
     #region Event raising code
 
     public B()
     {
         Timer t = new Timer(2000);
         t.Elapsed += (sender, args) => this.OnBE1(EventArgs.Empty);
         t.Start();
     }
 
     #endregion
 }

Passing the delegate

Lets see another technique for this event forwarding.
class A
{
    B bObject = new B();
   
    public event EventHandler AE1
    {
        add
        {
            this.bObject.BE1 += value;
        }
        remove
        {
            this.bObject.BE1 -= value;
        }
 
    }
}
Hope this property kind of syntax is familiar to all the .Net devs though it not used daily.
What are the differences?

Receive and fire

Passing delegate

The delegate of events can be different Delegates should be same
Even if the inner object is recreated there is no difference If the inner object is recreated event will not propagate
The sender of event will be originator classThe sender will be always the inner class
The intermediate class has to deal with dynamic event subscription in case there are multiple threadsIntermediate class don't need need to worry much about multiple threads
Happy coding.

No comments: