任何方式来捕获我不拥有的线程上发生的异常? [英] Any way to catch an exception occurring on a thread I don't own?

查看:154
本文介绍了任何方式来捕获我不拥有的线程上发生的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个肮脏的第三方图书馆,因为不幸的是我别无选择。当我调用它时,这个库会在内部创建一堆线程,偶尔在其中一个线程上抛出一个NullReferenceException。有没有什么办法可以捕捉这些例外,即使我不拥有抛出它们的线程?我无法更改第三方代码。

I'm using a crappy third party library because unfortunately I have no choice. This library creates a bunch of threads internally when I call it, and occasionally throws a NullReferenceException on one of these threads. Is there any way for me to catch these exceptions even though I don't own the thread that throws them? I have no way to change the third party code.

作为显示问题的简单示例:

As a simple example to show the problem:

public static void main()
{
    try
    {
        var crappyLib = new CrappyLibrary();
        crappyLib.DoCrappyThings();
    }
    catch
    {
        Console.WriteLine("This never happens");
    }
}

// I do not own the following code, I can't change it
public class CrappyLibrary
{
    public void DoCrappyThings()
    {
        var t = new Thread(DoWork);
        t.Start();
    }
    private void DoWork()
    {
        throw new ThisLibrarySucksException();
    }
}


推荐答案

在描述的情况下最令我担心的事情是第三方lib内的异常线程终止。一旦线程抛出,你将无法通过正确的方式捕获异常 ,因为你不是线程调用的所有者(并且它不知道它应该将异常传播给你;不像它)发生在TPL,让我们说)。因此,即使通过全局处理程序处理这种异常,这可能是不正确的方式,因为在任何这种异常之后,lib可能会出现在不一致的状态。

The thing worrying me most in the described case is abnormal thread termination inside that 3rd-party lib. Once a thread is throwing, you can't catch the exception via correct way because you're not the owner of that thread invocation (and it has no idea it should propagate the exception to you; unlike it happens in TPL, let say). So even if handling such exceptions via a global handler this could be incorrect way because the lib can appear in non-consistent state after any of such exceptions.

所以这里的安全方式是将lib放在一些范围内,并在任何异常之后重新启动范围。让我们说,把lib加载到单独的域里。

So the safe way here is to isolate the lib inside some scope and re-launch the scope after any exception. Let say, to load the lib into separate domain.

这篇关于任何方式来捕获我不拥有的线程上发生的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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