In a C# winforms program, I have an event that fires when someone attempts to rename a project. In the EventArgs for that event, I have a “Cancel” property that the event listeners can set to true to (ideally) cancel the rename (if the name is already in use, for example):
ProjectRenamedEventArgs args = new ProjectRenamedEventArgs(oldName, newName);
if (NameChanged != null)
NameChanged(this, args);
if (args.Cancel)
{
// Cancel
}
else
{
// Continue
}
The problem is, the “if (args.Cancel….” line is never reached. I’m guessing that execution is continuing right after the event is fired, and thus args.Cancel is always false so the rename always happens. How would I make execution halt until all of the event listeners have finished their work (giving args.Cancel a chance to be set to true).
I am assuming this is possible because many of the windows forms EventArgs have a Cancel property that allow for whatever just happened to be cancelled (changing the label on a TreeView’s TreeNode, for example).
You say: “The problem is, the ‘if (args.Cancel….” line is never reached’
This tells me that your event handler(s) wired to NameChanged are not returning. Another possibility is that one of these handlers is throwing an unhandled exception, and the above code in your example is swallowing the exception.
-Oisin