English 中文(简体)
BeginInvoke抛出异常
原标题:BeginInvoke throws exception
  • 时间:2010-02-18 09:30:04
  •  标签:
  • c#
  • delegates

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

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:

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()看起来很奇怪。

问题回答

实际上,当你叫EnInvoke时,这一例外被抓住,并再次被推翻,以便赶上你要求Envoke的尝试。

您可能会发现这篇文章有用 http://msdn.microsoft.com/en-us/magazine/cc163467.aspx





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签