c# - Blocking and waiting for an event -


It sometimes wants to block your thread while waiting for an event.

I usually do this like something:

  Private AutoResetEvent _autoResetEvent = New AutoResetEvent (wrong); Private Zero OnEvent (Object Sender, EventArgs e) {_autoResetEvent.Set (); } // ... button. Click + = ONVent; Try {_autoResetEvent.WaitOne (); } Finally {button.Click = = OnEvent; }  

However, it seems that it should be something that I could get into a normal class (or maybe anything that already exists in the framework).

I would like to be able to do something like this:

  EventWaiter ew = new eventwitter (click button); Ew.WaitOne (); EventWeeter EV = 2 new eventwitter (form.Closing); Ew2.WaitOne ();  

But I am not getting any way to create such a class (I can not find a good way to pass the incident in the form of an argument). Can anyone help?

Why it may be useful, consider this:

  var status = ShowStatusForm (); Status.ShowInsertUsbStick (); Bull was canceled = waitfourUSBusinessOrakanal (); If (Cancel!) {Status.ShowWritingOnUsbStick (); WriteOnUsbStick (); Status.AskUserToRemoveUsbStick (); WaitForUsbStickToBeRemoved (); Status.ShowFinished (); } And {status.ShowCancelled (); } Status.WaitUntilUserPressesDone ();  

It is more readable than concise code written with very brief and many arguments spread between several ways. But to prepare WaitForUsbStickOrCancel (), WaitForUsbStickToBeRemoved and WaitUntilUserPresses () (assuming we receive an event when USB sticks are included or removed) I need to replenish "EventWaiter" every time Of course you need to have GUI -Trade has to be careful to run it anytime, but sometimes it is a good credit for easy code.

Optional will appear something like this:

  var status = ShowStatusForm (); Status.ShowInsertUsbStick (); UsbHandler.Inserted + = OnStream; Event. Cancel + = Cancel; // ... Undefined on zero (/*..*/) {usbHandler.Inserted - = OnInsterted; Status.ShowWritingOnUsbStick (); Law Invocor Mile = () = & gt; WriteOnUsbStick (); Mi.BeginInvoke (writing, void); } Zero write writing (/*..*/) {/ * Endwok * / status Esuasaratomovuisbible (); Usbhandler.Removed + = Deleted; } Zero-free (/*..*/) {usbHandler.Removed - = reflected; Status.ShowFinished (); Event. Don + = ondone; Of course, that flow is so far linear, it is always very hard to read, but when it is, I like the first style is. 

This ShowMessage () and Forms. Shodiogy () is comparable to using - even if some "events" are not blocked (although they will run a message-loop when they call GUI-thread).

Do not pass an event, pass a delegation that matches the event handler signature. It really seems to be a hack for me, so be aware of potential dead lock issues.


Comments