voroninp voroninp - 2 months ago 5x
C# Question

How to not let the sender receive the message it sent?

Some of my classes send and receive message of the same type and I want them not to react on the messages they've sent.

The only way I see now is explicit sender's call to

prior sending the message and then calling
again after message is sent. This is fine but it requires quite a bit of boilerplate code.

It would be nice to have something like
where messenger ignores the sender if finds it in the list of the recipients.

Does IMessenger support this some way?


As far as I see, that's not possible. Neither the interface nor the implementation have facilities for this as they don't even know who the sender is.

The easiest approach would be to add the sender as a property to the message. This would greatly reduce the boilerplate code and would be safer than Register and Unregister in multi-threaded scenarios.

You could register your message like so:

messenger.Register(this, m => {
                                  if(m.Sender == this)
                              } );

If this is a common scenario on your code you could even create an interface or base class for that Sender property and extension methods for Register and Send that handle it.