开发者

I can't catch exceptions in an Invoked delegate

开发者 https://www.devze.com 2023-03-25 19:28 出处:网络
I have a delegate which is attached to an event in the Excel interop component. The goal is to update a winforms control with updated info from Excel. Since I\'m changing Control properties I need to

I have a delegate which is attached to an event in the Excel interop component. The goal is to update a winforms control with updated info from Excel. Since I'm changing Control properties I need to use Invoke:

public delegate void DataGridViewUpdate(object[,] data);

...

excel.InteractiveEdit( delegate(object[,] data) { 
    Invoke(new Common.DataGridViewUpdate(back_from_excel), new object[] { data }); 
});

...

private void back_from_excel(object[,] data) {
    // datagridview updating code
    // an exception is thrown here !
}

(This code is in the Form class that I'm updating so it's Invoking on this)

Basically my problem is that when an exception occurs in the back_from_excel(object[,] data)开发者_开发知识库 method, the debugger doesn't catch it. I know the delegate is running in the correct UI thread because I have no problems manipulating form controls.

Specifically what happens is that when back_from_excel hits an unhandled exception, it stops executing at that point. The rest of the application continues running and is responsive. The debugger doesn't pause. The output pane shows:

A first chance exception of type 'System.NullReferenceException' occurred in My Application.exe
A first chance exception of type 'System.NullReferenceException' occurred in System.Windows.Forms.dll

It doesn't give me any hints about which line caused the problem, just that it's somewhere in the .exe.

My question is: am I doing the Invoke thing right? It seems kind of strange to have delegate - Invoke - delegate chained together like that, but I do need to pass a delegate that Invokes a delegate. Is my problem in Visual Studio rather than in C#? If so how do I get the debugger re-attached to that UI thread?


A "first chance exception" indicates that an exception was thrown, but that it was caught at some point. Since you're passing a delegate to the InteractiveEdit method, that method can easily swallow any exceptions produced by the delegate.

By default, Visual Studio will only catch exceptions that don't get caught. If you want to catch all exceptions, regardless of whether they are caught, you need to configure Visual Studio to break on all exceptions. See this link for details on how to do this.

0

精彩评论

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

关注公众号