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 eve
You have to wait the call that raise the event and then check the flag in your EventArgs (in particular CancelEventArgs).
Easy:
Do you need code samples?
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;
}
}
}
What I needed was a way to stop the subscribers from receiving the event after a subscriber canceled it. In my situation I don't want the event to further propagate to the other subscribers after some subscriber canceled it. I have implemented this using custom event handling:
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");
}
}
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)
{
// ...
}