0

Class A has an event. Class B wants to subscribe to it. Class B has an event and class A wants to subscribe to it.

I tried by creating object of class B in A and class A in B. But it's a deadlock.

I need help here...

Please check this image

Grey rectangles must be events. Arrow indicates that an event has to be raised from class to class

class A
{
B b;
public event EventHandler eventA;

OnEventA()
{
eventA();
}

public A()
{
b= new B();
b.eventB += DoSomethingElse();
}

}


class B
{
A a;
public B()
{
    a= new A();
    a.eventA += DoSomething();
}
public event EventHandler eventB;

OnEventB()
{
eventB();
}


}
Anu
  • 43
  • 6

2 Answers2

1

Here's the code you need:

class A
{
    B b;
    public event EventHandler eventA;

    void OnEventA()
    {
        var ea = this.eventA;
        if (ea != null)
        {
            ea(this, new EventArgs());
        }
    }

    public A()
    {
        this.b = new B(this);
        this.b.eventB += DoSomethingElse;
    }

    private void DoSomethingElse(object sender, EventArgs e)
    {
    }
}

class B
{
    A a;
    public B(A a)
    {
        this.a = a;
        this.a.eventA += DoSomething;
    }
    public event EventHandler eventB;

    void OnEventB()
    {
        var eb = this.eventB;
        if (eb != null)
        {
            eb(this, new EventArgs());
        }       
    }

    private void DoSomething(object sender, EventArgs e)
    {
    }   
}
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
  • You saved my day. I totally forgot the concept of Parameterized Constructors. Thanks a ton. :) – Anu Jul 10 '17 at 05:35
1

Assuming your issue is that you don't get the right instances to talk to each other, here's one approach that might help you:

In you constructor for type A, create the instance of type B and set the reference to your current instance of A (this).

public A()
{
    // give B reference to A
    b = new B(this);
    // subscribe A to B's event
    b.eventB += DoSomethingElse();
}

In order for this to work you'll need to have the constructor of type B accept a reference to an A like this:

public B(A a)
{
    // subscribe B to A's event
    a.eventA += DoSomething();
}

You may also want to read up on unsubscribing from the events in order to make sure that you release resources properly. Check these links:

What best practices for cleaning up event handler references?

Should I always disconnect event handlers in the Dispose method?

dnickless
  • 10,733
  • 1
  • 19
  • 34