【发布时间】:2015-06-15 15:17:17
【问题描述】:
我正在使用一个糟糕的第三方库,因为不幸的是我别无选择。当我调用这个库时,它会在内部创建一堆线程,并且偶尔会在其中一个线程上抛出 NullReferenceException。即使我不拥有引发它们的线程,我有什么方法可以捕获这些异常吗?我无法更改第三方代码。
作为一个简单的例子来说明问题:
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();
}
}
【问题讨论】:
-
你能在你使用的第三方代码周围使用
try...catch吗? -
可以,但是异常不会传播到调用线程。
-
通常,在 .NET Web 应用程序中,您在 global.asax -> void Application_Error(object sender, EventArgs e) 中有一个事件 - 您可以在其中捕获应用程序中发生的所有错误。你在做什么类型的应用程序?
-
建议的线程没有回答问题,我有兴趣捕获我不拥有的线程的异常,因此我无法尝试捕获异常,它在我无权访问的堆栈上执行.
-
这不是一个骗局,因为 OP 无法更改用于启动线程的代码
标签: c# multithreading exception