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.
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.)
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With