QueueBackgroundWorkItem抛出ThreadAbortException

时间:2016-05-10 08:41:09

标签: c# multithreading asp.net-web-api2 .net-4.5.2

我正在尝试从WebAPI调用中排队后台工作者:

    public string TestThreadAbortException()
    {
        InitToolkit(DebugLevel.ERROR, 11937, true); // Initialize Logger, DB etc.
        var result = MyMethod(); // Runs through!
        DebugController.DoAfter(5.Seconds(), MyAction); // waits 5 seconds, and then calls MyMethod, waiting 20 seconds, but throws ThreadAbortException after 4 to 5 seconds into MyMethod
        return result;
    }

    private string MyMethod()
    {
        Thread.Sleep(20000);
        return "Test";
    }

    private void MyAction(Logger logger)
    {
        logger.Log(MyMethod());
    }


    public static void DoAfter(TimeSpan waitFor, Action<Logger> action)
    {
        HostingEnvironment.QueueBackgroundWorkItem(async ct =>
        {
            await Task.Delay(waitFor);
            DatabaseLogger logger = new DatabaseLogger();
            logger.Log("Executing " + action.Method.Name + ", " + DateTime.Now.ToLongTimeString());
            try
            {
                action(logger);
                logger.Log("Successfully executed " + action.Method.Name + ", " + DateTime.Now.ToLongTimeString());
            }
            catch (Exception e)
            {
                logger.Log("Error in " + action.Method.Name + ": " + e.Message + ", " + DateTime.Now.ToLongTimeString());
            }
            finally
            {
                logger.CloseDatabase();
            }
        });
    }

这会生成以下日志:

Executing MyAction, 10:30:51
Error in MyAction: Der Thread wurde abgebrochen., 10:30:55

但是我如何找到线程被中止的原因,或者我如何绕过这个问题呢?我知道在帖子中调用了Abort(),但我不明白为什么以及在哪里 - 我的代码中没有调用Abort()

0 个答案:

没有答案