Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensuring that we subscribe only once to an event

Tags:

c#

events

Here is my question: if I want to ensure, that a handler is subscribed only once, is it correct to subscribe in this way:

x.Event -= Handler;
x.Event += Handler;

Idea is "try unsubscribe, even if we were not subscribed", then subscribe when we are 100% not subscribed.

Is this idea correct, and if not - why? Googled it for some time, cannot seem to find the answer myself.

like image 700
deafsheep Avatar asked Apr 13 '11 10:04

deafsheep


2 Answers

So long as you do that everywhere you're subscribing that handler, it should be fine. But if you subscribe 100 times and then run that code, you're still going to be left with 100 subscriptions.

(I'm assuming you're only using a single thread, by the way. There's a race condition if two threads execute that code at the same time... they could both unsubscribe an then both subscribe, leaving two active subscriptions.)

like image 117
Jon Skeet Avatar answered Oct 01 '22 19:10

Jon Skeet


What you have will not throw any exceptions, so it will work as intended -- but it's not very clear code.

I would very much prefer a test with a boolean flag instead:

if(!subscribed) {
    x.Event += Handler;
}
like image 38
Jon Avatar answered Oct 01 '22 20:10

Jon