本文介绍了TaskCanceledException与ContinueWith的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图弄清楚为什么为什么要获取TaskCanceledException来获取一些最近开始行为异常的异步代码.我已将问题简化为一个小的代码片段,这让我抓狂了:

I've been trying to figure out why I'm getting a TaskCanceledException for a bit of async code that has recently started misbehaving. I've reduced my issue down to a small code snippet that has me scratching my head:

static void Main(string[] args)
{
    RunTest();
}

private static void RunTest()
{
    Task.Delay(1000).ContinueWith(t => Console.WriteLine("{0}", t.Exception), TaskContinuationOptions.OnlyOnFaulted).Wait();
}

据我所知,这应该暂停片刻然后关闭.不会调用ContinueWith(这仅适用于我的实际用例).但是,相反,我收到了TaskCanceledException,我不知道那是哪里来的!

As far as I'm aware, this should simply pause for a second and then close. The ContinueWith won't be called (this only applies to my actual use-case). However, instead I'm getting a TaskCanceledException and I've no idea where that is coming from!

推荐答案

您使用了错误的taskcontinuation选项:

You are using the wrong taskcontinuationoption:

请参阅以下链接: https://msdn.microsoft.com/zh-cn/library/system.threading.tasks.taskcontinuationoptions%28v=vs.110%29.aspx

它说:指定仅在其前任引发未处理的异常时才应调度该继续任务.此选项对多任务继续无效.

It says :Specifies that the continuation task should be scheduled only if its antecedent threw an unhandled exception. This option is not valid for multi-task continuations.

这篇关于TaskCanceledException与ContinueWith的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 07:46