Is there a generally accepted best practice for creating an event handler that unsubscribes itself?
For example, the first thing I came up with is something like:
// Foo.cs // ... Bar bar = new Bar(); EventHandler handler = new EventHandler(bar.HandlerMethod); bar.HandlerToUnsubscribe = handler; eventSource.EventName += handler; // ...
// Bar.cs class Bar { /* add'l req'd state */ // .ctor public EventHandler HandlerToUnsubscribe { get; set; } public void HandlerMethod(object sender, EventArgs args) { // Do what must be done w/ add'l req'd state ((EventSourceType)sender).EventName -= this.HandlerToUnsubscribe; } }
Saying this sounds hacky / bad is an understatement. It is closely related to time dependence ( HandlerToUnsubscribe must be assigned the exact value at the exact time). I feel that in this case I have to play the role of a complicator - is there something stupid or simple that I am missing?
Context:
I am creating a binding between the user interface and the proprietary command infrastructure in Winforms (using the useful ICommand in System.Windows.Input). One aspect of the binding infrastructure is that users who create a binding between a component of a UI command (for example, a toolbar button or menu item) are able to listen to the CanExecuteChanged command and then update the state of the user interface based on this - usually setting the Enabled property true or false .
The technique usually works quite well, but there are ways to trigger the event before creating the ui component descriptor. I am trying to ensure that the provided handler will not be launched if the handle has not been created. As a result, I consider providing a common helper class (" Bar ") that will facilitate implementation. The purpose of Bar is to check if an appropriate descriptor exists. If so, great! If not, it will subscribe to the corresponding IsHandleCreated event IsHandleCreated that the handlers included in the package will be launched when the handle is created. (This is important b / c, the client can set its bindings in the UI.ctor before the descriptor exists.) I want this subscription to be completely transparent, and therefore I also want each event handler to automatically unsubscribe itself from IsHandleCreated after completion work.
I'm still at the point where I'm trying to figure out if this is a good idea, so I haven't generalized the concept yet. I applied it directly to ToolStripItems in this case to check what the idea sounds like. I have not sold it yet.
I understand that I also have the opportunity to simply indicate that bindings can only be created after creating the user interface handle in the OnLoad event of the form (for example,). I know this can work, I have done this in the past. I would like to see if I can facilitate this particular requirement in this case. If itβs even practical.
c # event-handling
Greg D Oct 12 '09 at 14:14 2009-10-12 14:14
source share