Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BeginInvoke throws exception

Tags:

c#

delegates

I have the following problem. FindRoot is actually in a third party dll and I do not have control over it. It has to be called via Begin invoke. Sometimes, the FindRoot method throws exception. This causes my whole application to crash. Now how do I prevent my application from crashing even if FindRoot throws exception.

delegate void AddRoot(double number);
public static void FindRoot(double number)
{
    throw new Exception();/// sometimes is thrown.

}

static void back_DoWork(object sender, DoWorkEventArgs e)
{
    AddRoot root = FindRoot;
    root.BeginInvoke(12.0, root.EndInvoke, root);

}
like image 794
Prashant Avatar asked Feb 18 '10 09:02

Prashant


2 Answers

Use a callback instead of directly calling EndInvoke:

using System.Runtime.Remoting.Messaging;
...
static void back_DoWork() 
{
    AddRoot root = FindRoot;
    root.BeginInvoke(12.0, new AsyncCallback(callback), root);
}

static void callback(IAsyncResult result) 
{
    AddRoot dlg = (AddRoot)(((AsyncResult)result).AsyncDelegate);

    try 
    {
        dlg.EndInvoke(result);
    }
    catch (Exception ex) 
    {
        Console.WriteLine(ex.Message);
    }
}

Btw: it looks to me like you are already calling this code from a background thread. Starting yet another thread to run FindRoot() looks strange.

like image 130
Hans Passant Avatar answered Nov 19 '22 08:11

Hans Passant


Actually the exception is caught and re-thrown when you call EndInvoke, so to catch it you need to use try around your call to EndInvoke.

You may find this article useful http://msdn.microsoft.com/en-us/magazine/cc163467.aspx

like image 22
Brian Rasmussen Avatar answered Nov 19 '22 09:11

Brian Rasmussen