调试时出现 ThreadAbortException [英] ThreadAbortException on debugging

查看:70
本文介绍了调试时出现 ThreadAbortException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这种方式来执行异步 void 方法并访问局部变量:

I am using this way to execute async void methods with access to local variables:

static void RunAsync(object var1, object var2)
{
    ThreadStart work = delegate
    {
        try
        {
            Statement1(var1);
            Statement2(var2);
            // etc
        }
        catch (Exception e) { }
    };
    new Thread(work).Start();
}

在 Visual Studio 中通过单元测试进行调试通常会导致 ThreadAbortException,但运行测试(和运行代码)可以正常工作.

Debugging through unit test in Visual Studio often causes ThreadAbortException, but running tests (and running code) works fine.

这是什么原因造成的?

推荐答案

发生这种情况是因为当您调用 RunAsync 方法时,它会创建线程,但返回到 TestMethod,在线程完成之前测试完成.测试完成后,它会尝试中止所有线程,因此您会收到该异常.您必须使用 Join 等待线程完成.

It happens because when you call RunAsync method it creates the thread but returns to TestMethod where the test finishes before the thread finishes. When the test finishes it tries to abort all the threads so you get that exception. You must wait until the thread finishes by using a Join.

建议:

Thread t;
static void RunAsync(object var1, object var2)
{
    ThreadStart work = delegate
    {
        try
        {
            Statement1(var1);
            Statement2(var2);
            // etc
        }
        catch (Exception e) { }
    };
    t=new Thread(work);
    t.Start();
}
[TestMethod]
public void TestMethod()
{
   RunAsync();

   DoOtherStuff();
   if(t!=null)
      t.Join();

}

这篇关于调试时出现 ThreadAbortException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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