Avoid duplicate event subscriptions in C# -
How would you suggest the best way to avoid duplicate event subscriptions? If this line of code executes in two places, the event will run twice. I am trying to avoid subscribing to the third party event twice.
theOBject.TheEvent + = RunMyCode; In my representative setter, I can run it effectively ...
theOBject .Event - = RunMyCode; TheOBject.TheEvent + = RunMyCode; But is this the best way?
I think, in the most effective way, create an asset to your event and concurrency as this Adding the locks to this :
Private EventHandler _theEvent; Private object _eventLock = new object (); Public Event EventHandler TheEvent {add {lock (_eventLock) {_theEvent - = value; _theEvent + = value; }} Remove {Lock (_eventLock) {_theEvent - = Value; }}}
Comments
Post a Comment