BeginInvoke throws exception(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 抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:BeginInvoke 抛出异常


基础教程推荐
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01