How can I check if an event has been subscribed to, in .NET?
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.Re开发者_如何学编程ceiveCompleted' can only appear on the left hand side of += or -=
I know this is embarrassingly simple .. but I'm stumped :( Any suggestions?
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).
you cannot do this from subscriber to the event. Only publisher can check if there are any subscribers. You will need to keep track of subscription using some other mechanism in your class like:
UploadFolderMessageQueue.ReceiveCompleted += UploadMSMQReceiveCompleted;
bool handlerAttached=true;
then you can use this:
if(handlerAttached)
{
//DO YOUR STUFF
}
The null test can only be performed within the class that declares the event (i.e. the UploadFolderMessageQueue type.)
1) If you have access to the source of this class you can add a method or property that does the test and returns a boolean result that you can check before subscribing.
2) If you cannot modify the declaring class, and you are only checking for re-subscriptions from your own code, you can separately record the subscription in a boolean variable, and then check that variable before attempting to (re) subscribe.
3) If you cannot change the declaring class and you are checking for subscriptions from code other than your own, there doesn't appear to be a solution.
精彩评论