开发者

C# Wait until event listeners have finished

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 na开发者_如何学JAVAme 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


Events are synchronous by default = you current code should work.

You need to use BeginInvoke to make events asynchronous (the thingy that you want to avoid)


How would I make execution halt until all of the event listeners have finished their work

It does halt until all handlers have executed, it's the default behavior if you call NameChanged directly. Try to step into the event handlers to see what's happening


The only reason for not calling if (args.Cancel) .. i can think of is that there is an uncaught exception inside one of the eventhandlers.

Note i sometime have problems with the vs2008/vs2010 debugger that continues operation of the main app instead of stopping behind the event-call. you can check this if you put a breakpoint at if (args.Cancel) ..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜