Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a cancel event in C#

Tags:

I know that in C#, there are several built in events that pass a parameter ("Cancel") which if set to true will stop further execution in the object that raised the event.

How would you implement an event where the raising object was able to keep track of a property in the EventArgs?

Here is a WinForms example of what I am trying to do:
http://msdn.microsoft.com/en-us/library/system.componentmodel.canceleventargs.cancel.aspx

Thank you.

like image 677
Sako73 Avatar asked Mar 02 '10 20:03

Sako73


2 Answers

It's really easy.

private event _myEvent;  // ...  // Create the event args CancelEventArgs args = new CancelEventArgs();  // Fire the event _myEvent.DynamicInvoke(new object[] { this, args });  // Check the result when the event handler returns if (args.Cancel) {     // ... }
like image 97
Jon Seigel Avatar answered Oct 13 '22 00:10

Jon Seigel


Here is the way that I avoid calling further subscribers once one of them asserts cancel:

var tmp = AutoBalanceTriggered; if (tmp != null) {     var args = new CancelEventArgs();     foreach (EventHandler<CancelEventArgs> t in tmp.GetInvocationList())     {         t(this, args);         if (args.Cancel)  // a client cancelled the operation         {             break;         }     } } 
like image 45
Dave Tillman Avatar answered Oct 12 '22 23:10

Dave Tillman