问题描述
我有以下问题.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 抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!