Charles
Charles

Reputation: 33

Exception not caught when using Invoke

I am in a thread which changes data which should be displayed in a dialog (if one is open) so I have the following function:

public void UpdateDialog() {
 try {
  if (dlg != null)
   Application.Current.Dispatcher.Invoke((Action) delegate {
    dlg.Draw();
   });
 } catch {}
}

Everything is fine until the user closes the box (in the UI thread). Then dlg may become null after the check and a NullReferenceException is thrown which is not caught by the try/catch block.

I'm guessing that dlg checked as non-null and is passed to the UI thread which queues up the Draw request. Then the dialog is closed before the Draw method is actually called. Then the UI thread throws the exception which is not caught in the thread I'm in because it was thrown in a different thread.

I've tried putting a lock on the dlg property but no change.

Any ideas as to how to handle this? (I just need to ignore the exception because the dlg is closed anyway)

Why is the exception not handled by the Try/Catch block?

Upvotes: 1

Views: 1014

Answers (1)

Renat
Renat

Reputation: 8972

It's being executed in the different thread, so it's not under your try-catch.

This would catch it:

Application.Current.Dispatcher.Invoke(new Action(() => {
    try 
    {
        dlg?.Draw(); 
    } 
    catch {}
}));

Fixed with extra checking for null, as mentioned by @Panagiotis Kanavos

Edit: this is a toy example, please avoid suppressing exceptions in real code, and don't suppress them in the business logic because this could lead to corrupted state.

Upvotes: 1

Related Questions