I am using an event-based API and want to have a certain event handling method be called only once. (Note that I have another method which is always handling the event, but I want to add another handler for certain situations and have it only execute once.)
Is it possible/encouraged to unsubscribe from an event inside the event handler? E.g.
private void OnEventRaised(object sender, EventArgs e) {
_eventRaisingObject.EventRaised -= OnEventRaised;
... // Do normal code
}
What sort of cross-threading issues should I be concerned with in this approach?
Secondly, is it possible to have the event handler be called only once when it is an anonymous method? E.g.
_eventRaisingObject.EventRaised += (sender, e) => {
// Unsubscribe?
... // Do normal code
}
Currently, I am using an anonymous method and simply checking a boolean, but I think that it would be better (less overhead and potential bugs) to unsubscribe when the work is done - perhaps this assumption is incorrect. One problem I foresee with checking a boolean is that, if the situation needs repeating (so that the anonymous event handler is added again), the shared boolean might allow the anonymous methods to be called multiple times on different threads.