Since Messenger uses weak reference to a target, message dispatch does not work if I use lambda with closure. This works:
```
void Register(SomeClass obj)
{
Messenger.Default.Register<SomeMessage>(this, msg=>
{
MessageBox.Show(...);; // obj is not used, no closure
});
}
```
This does not work:
void Register(SomeClass obj)
{
Messenger.Default.Register<SomeMessage>(this, msg=>
{
MessageBox.Show(...);;
obj.DoSomething();
});
}
When I send SomeMessage the handler is not called. The reason for that is that in the first case compiler generates just a method, but in the second case it generates a class that holds captured parameters ("obj" in our case). Register() is then called with a delegate pointing to an instance of that hidden class. Since messenger uses weak references, this instance quickly gets garbage collected, the reference dies, and the handler can no longer be called.
```
void Register(SomeClass obj)
{
Messenger.Default.Register<SomeMessage>(this, msg=>
{
MessageBox.Show(...);; // obj is not used, no closure
});
}
```
This does not work:
void Register(SomeClass obj)
{
Messenger.Default.Register<SomeMessage>(this, msg=>
{
MessageBox.Show(...);;
obj.DoSomething();
});
}
When I send SomeMessage the handler is not called. The reason for that is that in the first case compiler generates just a method, but in the second case it generates a class that holds captured parameters ("obj" in our case). Register() is then called with a delegate pointing to an instance of that hidden class. Since messenger uses weak references, this instance quickly gets garbage collected, the reference dies, and the handler can no longer be called.