Unregistering from Messenger


I have been using your classes for a while now and I have a question regarding the Messenger class. I your WpfDemoApp, from the NumberChangeLogView constructor, you register like the following:
            new Action(() => _scrollViewer.ScrollToBottom()));
If I debug step into Register method and look at the Action object, callback, in Watch list the value is said to be: {Method = {Void <.ctor>b__0()}}
My question is: why is it the constructor (ctor) displayed here? Why isn't it the simply method ScrollToBottom.
The reason of my question? I tried to add an unregister method to your Messenger to be called like the following:
            new Action(() => _scrollViewer.ScrollToBottom()));
That call should retrieve the action registered and remove it from the map list. The problem is, since that call will be made elsewhere than in the constructor, I end up having a different action object which is not equal to the one passed in parameter on registration. So I cannot retrieve the action and unregister it.
To give an example, in my project I registered a save message from my constructor:
            new Action(() => this.Save()));
So in the messenger, the action had a value of (in debug window Watch List):
{Method = {Void <.ctor>b__0()}}
And I unregistered from my method OnDispose, and the action came out to be:
{Method = {Void <OnDispose>b__2()}}
I know you said it is unnecessary to unregister because of weakreferences, but I have a case where I would like to unregister manually so I was wondering what is your thought on it. How can it be implemented?


JoshSmithOnWpf wrote Oct 15, 2009 at 3:55 PM

The method name is {Void <.ctor>b__0()}} because the Action object contains a lambda expression as its callback. That lambda expression is basically turned into a separate method by the compiler, and it is assigned a compiler-generated name. If you want to unregister a callback, don't use lambda expressions. Instead, when creating the Action object, pass in the name of a callback method that you created (so that it doesn't have a compiler-generated name).


GIJoe wrote Oct 15, 2009 at 4:26 PM

Hi Josh,

Thanks for the answer. It worked. But is there a drawback doing it this way? I mean did you use lambda expression?


GIJoe wrote Oct 15, 2009 at 4:27 PM

Little mistake:

Thanks for the answer. It worked. But is there a drawback doing it this way? I mean why did you use lambda expression?


JoshSmithOnWpf wrote Oct 15, 2009 at 5:27 PM

I used a lambda expression in my example because I had no need to unregister. A lambda expression, at the end of the day, is just a delegate (i.e. a strongly typed callback).

wrote Feb 21, 2013 at 11:05 PM