BeginInvoke抛出异常 [英] BeginInvoke throws exception

查看:209
本文介绍了BeginInvoke抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题。 FindRoot实际上是在第三方dll,我没有控制权。 必须通过开始调用调用。有时,FindRoot方法会引发异常。这导致我的整个应用程序崩溃。现在如何防止我的应用程序崩溃,即使FindRoot抛出异常。

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

}


推荐答案

使用回调而不是直接调用EndInvoke:

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:看起来像我已经在打电话这个代码来自一个后台线程。开始另一个运行FindRoot()的线程看起来很奇怪。

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.

这篇关于BeginInvoke抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆