BeginInvoke 抛出异常

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

问题描述

我有以下问题.FindRoot 实际上在第三方 dll 中,我无法控制它.必须通过 Begin invoke 调用.有时,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);
    }
}

顺便说一句:在我看来你已经从后台线程调用了这段代码.启动另一个线程来运行 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 抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)