我知道在C#中,有几个内置事件传递参数(“取消”),如果设置为 true 将停止在引发事件的对象中进一步执行。
如何实现一个事件,其中提升对象能够跟踪EventArgs中的属性?
以下是我尝试执行的操作的WinForms示例:
http://msdn.microsoft.com/en-us/library/system.componentmodel.canceleventargs.cancel.aspx
谢谢。
答案 0 :(得分:16)
这很容易。
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)
{
// ...
}
答案 1 :(得分:13)
一旦其中一个断言取消,我就避免调用其他订阅者的方式:
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;
}
}
}
答案 2 :(得分:3)
我需要的是在订阅者取消订阅后阻止订阅者接收事件的方法。在我的情况下,我不希望事件在一些订阅者取消之后进一步传播给其他订阅者。 我使用自定义事件处理实现了这个:
public class Program
{
private static List<EventHandler<CancelEventArgs>> SubscribersList = new List<EventHandler<CancelEventArgs>>();
public static event EventHandler<CancelEventArgs> 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<CancelEventArgs> 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<CancelEventArgs>(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<CancelEventArgs>(program_TheEvent);
}
void program_TheEvent(object sender, CancelEventArgs e)
{
Console.WriteLine("Subscriber2: in program_TheEvent");
}
}
答案 3 :(得分:2)
易:
您需要代码示例吗?
答案 4 :(得分:0)
您必须等待引发事件的调用,然后检查EventArgs中的标志(特别是CancelEventArgs)。