Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

c# - BeginInvoke throws exception

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);

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...