Reputation: 2892
I have a code which should notify a delegate in one of service classes on receiving an event:
public class TestClass : ParentClass
{
public event EventHandler<string> MyDelegate;
public override void OnAction(Context context, Intent intent)
{
var handler = MyDelegate;
if (handler != null)
{
handler(this, "test");
}
}
}
I instantiate it by:
private TestClass mytest= new TestClass ();
And then assign it in one of the functions:
mytest.MyDelegate+= (sender, info) => {
};
The delegate never gets called. I have stepped through with debugger and I see that delegate is being assigned, but the check inside a class is always null... Cant figure out whats the problem...
Upvotes: 0
Views: 1576
Reputation: 4630
Sounds like an execution order issue. What could be happening is that OnAction
within TestClass
is being called before the delegate hookup. Try the following:
public class TestClass : ParentClass
{
public event EventHandler<string> MyDelegate;
public class TestClass(Action<string> myAction)
{
MyDelegate += myAction;
}
public override void OnAction(Context context, Intent intent)
{
var handler = MyDelegate;
if (handler != null)
{
handler(this, "test");
}
}
}
Just pass the delegate through the constructor, this should make sure its hooked up before any calls to OnAction()
You can pass through the handler in a couple ways:
1.) As an anonymous method:
private TestClass mytest= new TestClass ((sender, info) => { Console.WriteLine("Event Attached!") });
2.) Pass in the method group:
public class MyEventHandler(object sender, string e)
{
Console.WriteLine("Event Attached!");
}
private TestClass mytest= new TestClass(MyEventHandler);
I generally recommend the second way as it allows you to unhook the handler and do clean up once you are done with it:
myTest.MyDelegate -= MyEventHandler;
Upvotes: 1