I recently came across the need to allow consumers to prevent further execution of methods and I utilized an event driven system that allows the consumer to specify if the execution should cancel. I've tested it in a multi-threaded environment and everything is working as expected so as a simple solution it works as intended with no issues. However, I can't help but wonder where there are improvements that could be made as I've never dealt with event cancellations before.
Event Arguments Definition
public class CustomEventArgs {
public bool Cancel { get; set; } = false;
}
I'm not sure that a default value for the Cancel
property is a good idea here.
Object Definition
public class MyCustomObject {
public void Count(int countTo) {
if (ShouldCount()) {
for (int i = 0; i < countTo;)
Console.WriteLine(++i);
} else
Console.WriteLine("Counting process was cancelled by the consumer.");
Console.WriteLine("The counting process has completed.");
}
public event EventHandler<CustomEventArgs> OnStarting;
private bool ShouldCount()
{
Console.WriteLine("The counting process is starting.");
CustomEventArgs args = new CustomEventArgs();
OnStarting?.Invoke(this, args);
return !args.Cancel;
}
}
I believe that return !args.Cancel
is a little confusing to read as negative logic. Perhaps it should be return args.Cancel
and the method should be renamed to something like ShouldCancelCounting
and check for if (!ShouldCancelCounting())
instead of if (ShouldCount())
?
Consumption
private static bool CancelEvent = false;
private static void RunTest() {
CancelEvent = false;
MyCustomObject obj = new MyCustomObject();
obj.OnStarting += CountStarting;
obj.Count(100);
CancelEvent = true;
MyCustomObject obj = new MyCustomObject();
obj.OnStarting += CountStarting;
obj.Count(100);
}
private static void CountStarting(object sender, CustomEventArgs e) {
e.Cancel = CancelEvent;
}
What are some areas that are harder to follow with this implementation? Is there anything confusing about it in any way? Is there any official Microsoft documentation on implementing event cancellations? What are some potential gotchas with my implementation?