【发布时间】:2014-06-13 11:02:52
【问题描述】:
我有一个扩展方法。这里是:
public static void BeginInvokeWithAutoEnd(this EventHandler handler, object sender, EventArgs eventArgs)
{
var buffer = handler;
buffer.BeginInvoke(sender, eventArgs, buffer.EndInvoke, null);
}
为了测试它,有以下方法:
[TestMethod]
public void BeginInvokeWithAutoEnd_SubscribedMethodThrowsException_ExceptionCanBeCaught()
{
var multiThreadTest = new MultiThreadTest(2);//Class that helps to test asynchronous stuff
var thrown = false;
var ex = new Exception("OOoooOOo!");
EventHandler onHandler = (s, a) => { throw ex; };
UnhandledExceptionEventHandler currentDomainOnUnhandledException = (s, args) =>
{
thrown = args.ExceptionObject.Equals(ex);
multiThreadTest.Notify();
};
AppDomain.CurrentDomain.UnhandledException += currentDomainOnUnhandledException;
//Invokes Action from the parameter and waits for multiThreadTest.Notify(); method to be called, otherwise 2 seconds
multiThreadTest.Act(() => onHandler.BeginInvokeWithAutoEnd(this, EventArgs.Empty));
AppDomain.CurrentDomain.UnhandledException -= currentDomainOnUnhandledException;
Assert.IsTrue(thrown);
}
测试本身运行良好,但它随机破坏了我拥有的其他测试之一。当我查看损坏的测试时,它是这样写的:The agent process was stopped while the test was running.。这意味着在另一个线程中存在未处理的异常,而损坏的测试正在运行。
我不知道这怎么会发生。在这里将不胜感激。
【问题讨论】:
-
因为您正在线程池上开始工作,而不是等待它完成。
-
@usr 你能解释得更准确一点吗?我确实在等待
multiThreadTest.Notify();。如果这就是你的意思。 -
BeginInvokeWithAutoEnd 从不等待并立即返回。这意味着调用
Act的行也立即返回。这就是你想要的吗? -
@usr 方法
multiThreadTest.Act(...)调用它作为参数接收的Action,然后等待multiThreadTest.Notify();。 -
这是有道理的。发布更多代码,尤其是 Act。当您使用调试器单步执行代码时会发生什么?
标签: c# .net multithreading appdomain unhandled-exception