考虑以下情况

 var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(2));
        var startNew = Task.Factory.StartNew(() =>
        {
            var currentThread = Thread.CurrentThread;
            try
            {
                using (cancellationTokenSource.Token.Register(currentThread.Abort))
                    new AutoResetEvent(false).WaitOne(Timeout.InfiniteTimeSpan);
            }
            catch (ThreadAbortException abortException)
            {
                throw new TimeoutException("Operation timeouted", abortException);
            }
        }, cancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Current);
        startNew.ContinueWith(val => Console.WriteLine("Cancellation handled"), TaskContinuationOptions.OnlyOnCanceled);
        startNew.ContinueWith(val => Console.WriteLine("Fault handled"), TaskContinuationOptions.OnlyOnFaulted);
        startNew.ContinueWith(val => Console.WriteLine("Ran to completion handled"), TaskContinuationOptions.OnlyOnRanToCompletion);

搁置所有关于中止线程是邪恶的讨论,为什么这段代码没有使任务进入Faulted状态?但是删除catch块或调用
Thread.ResetAbort()

似乎可以解决问题

最佳答案

关于线程中止的工作方式:

try {
    try {
        try {
            Thread.CurrentThread.Abort();
        } catch(Exception e) {
            Console.WriteLine(e.GetType());
            throw new Exception();
        }
    } catch(Exception e) {
        Console.WriteLine(e.GetType());
    }
} catch(Exception e) {
    Console.WriteLine(e.GetType());
}

此代码打印:

System.Threading.ThreadAbortException
System.Exception
System.Threading.ThreadAbortException

因此,当将处理您的自定义异常时,应重新抛出ThreadAbortException



现在让我们来看一些source:
/// <summary>
/// Executes the task. This method will only be called once, and handles bookeeping associated with
/// self-replicating tasks, in addition to performing necessary exception marshaling.
/// </summary>
private void Execute()
{
    if (IsSelfReplicatingRoot)
    {
        ExecuteSelfReplicating(this);
    }
    else
    {
        try
        {
            InnerInvoke();
        }
        catch (ThreadAbortException tae)
        {
            // Don't record the TAE or call FinishThreadAbortedTask for a child replica task --
            // it's already been done downstream.
            if (!IsChildReplica)
            {
                // Record this exception in the task's exception list
                HandleException(tae);

                // This is a ThreadAbortException and it will be rethrown from this catch clause, causing us to
                // skip the regular Finish codepath. In order not to leave the task unfinished, we now call
                // FinishThreadAbortedTask here.
                FinishThreadAbortedTask(true, true);
            }
        }
        catch (Exception exn)
        {
            // Record this exception in the task's exception list
            HandleException(exn);
        }
    }
}

如您所见,ThreadAbortException案例有一个特殊的代码路径,可以将任务转移到故障状态。当您通过ThreadAbortException隐藏TimeoutException时,不会采用特殊的代码路径。因此,当常规代码路径通过将异常记录在任务的异常列表中来处理异常时,将重新抛出ThreadAbortException,这将阻止正确的任务转换为故障状态。

关于c# - 在Task中重新抛出异常不会使Task进入故障状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31574378/

10-13 08:24
查看更多