Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if an event has been subscribed to, in .NET?

Tags:

c#

.net

events

At one point in my code, i subscribe to the following event :-

UploadFolderMessageQueue.ReceiveCompleted += UploadMSMQReceiveCompleted;

works great and when the Message Queue's Recieved Completed event fires, my delegate handles it.

Now, I'm wanting to CHECK to see if the event has been subscribed to, before I subscribe to it. I get an compile time error when I do :-

// Compile Time Errors...
if (UploadFolderMessageQueue.ReceiveCompleted == null)
    {
        UploadFolderMessageQueue.ReceiveCompleted += UploadMSMQReceiveCompleted;
        UploadFolderMessageQueue.Formatter = 
            new XmlMessageFormatter(new[] {typeof (string)});
    }

The event 'System.Messaging.MessageQueue.ReceiveCompleted' can only appear on the left hand side of += or -=

I know this is embarrassingly simple .. but I'm stumped :( Any suggestions?

like image 537
Pure.Krome Avatar asked Aug 30 '10 04:08

Pure.Krome


1 Answers

If you need to make sure that there is only one subscriber you can use the following code:

UploadFolderMessageQueue.ReceiveCompleted -= UploadMSMQReceiveCompleted;
UploadFolderMessageQueue.ReceiveCompleted += UploadMSMQReceiveCompleted;

If UploadFolderMessageQueue.ReceiveCompleted is null then the first line will do nothing, in other case the event handler will be removed. That means UploadFolderMessageQueue.ReceiveCompleted will always have only one subscriber (of course if the UploadMSMQReceiveCompleted is the only one event handler for that event).

like image 135
bniwredyc Avatar answered Oct 05 '22 05:10

bniwredyc