如何在C#中实现取消事件

我知道在C#中,有几个内置事件传递参数(“取消”),如果设置为true,将停止在引发事件的对象中进一步执行。

如何实现一个事件,其中提升对象能够跟踪EventArgs中的属性?

这是我想要做的WinForms示例:
http://msdn.microsoft.com/en-us/library/system.componentmodel.canceleventargs.cancel.aspx

谢谢。

这真的很容易。

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) { // ... } 

一旦其中一个断言取消,我就避免调用其他订阅者的方式:

 var tmp = AutoBalanceTriggered; if (tmp != null) { var args = new CancelEventArgs(); foreach (EventHandler t in tmp.GetInvocationList()) { t(this, args); if (args.Cancel) // a client cancelled the operation { break; } } } 

我需要的是一种方法来阻止订阅者在订阅者取消它之后接收该事件。 在我的情况下,我不希望事件在一些订阅者取消之后进一步传播给其他订阅者。 我使用自定义事件处理实现了这个:

 public class Program { private static List> SubscribersList = new List>(); public static event EventHandler TheEvent { add { if (!SubscribersList.Contains(value)) { SubscribersList.Add(value); } } remove { if (SubscribersList.Contains(value)) { SubscribersList.Remove(value); } } } public static void RaiseTheEvent(object sender, CancelEventArgs cancelArgs) { foreach (EventHandler sub in SubscribersList) { sub(sender, cancelArgs); // Stop the Execution after a subscriber cancels the event if (cancelArgs.Cancel) { break; } } } static void Main(string[] args) { new Subscriber1(); new Subscriber2(); Console.WriteLine("Program: Raising the event"); CancelEventArgs cancelArgs = new CancelEventArgs(); RaiseTheEvent(null, cancelArgs); if (cancelArgs.Cancel) { Console.WriteLine("Program: The Event was Canceled"); } else { Console.WriteLine("Program: The Event was NOT Canceled"); } Console.ReadLine(); } } public class Subscriber1 { public Subscriber1() { Program.TheEvent += new EventHandler(program_TheEvent); } void program_TheEvent(object sender, CancelEventArgs e) { Console.WriteLine("Subscriber1: in program_TheEvent"); Console.WriteLine("Subscriber1: Canceling the event"); e.Cancel = true; } } public class Subscriber2 { public Subscriber2() { Program.TheEvent += new EventHandler(program_TheEvent); } void program_TheEvent(object sender, CancelEventArgs e) { Console.WriteLine("Subscriber2: in program_TheEvent"); } } 

简单:

  1. 创建CancelEventArgs(或您的自定义类型)的实例。
  2. 提升事件,传递该实例。
  3. 检查[1]上的Canceld属性。

你需要代码样本吗?

您必须等待引发事件的调用,然后检查EventArgs中的标志(特别是CancelEventArgs)。