[英]Trying to understand C# TaskContinuationOptions.OnlyOnFaulted
I am trying to understand C# TaskContinuationOptions.OnlyOnFaulted
and I wrote this simple example. 我试图理解C#
TaskContinuationOptions.OnlyOnFaulted
,我写了这个简单的例子。 I expect the continuation task to not run because there was no exception in the antecedent task but it runs anyway. 我希望继续任务不会运行,因为前一个任务中没有异常,但无论如何它都会运行。
var task = Task.Factory
.StartNew(() => { Console.WriteLine("Hello world!"); })
.ContinueWith((x, y) =>
{
Console.WriteLine("This should not get printed!");
}, TaskContinuationOptions.OnlyOnFaulted);
You need to look more closely at what overloads exist for ContinueWith()
, and especially what overload you're actually calling. 您需要更仔细地查看
ContinueWith()
存在的重载,尤其是您实际上正在调用的重载。
There is no overload for ContinueWith()
that takes only a delegate and a TaskContinuationOptions
value specifically. 没有使用
ContinueWith()
重载,该重载仅使用一个委托和一个TaskContinuationOptions
值。 The overload you're calling takes as parameters an Action<Task, object>
, and then any object
value, which is the "state" value passed to the Action<Task, object>
. 您要调用的重载将
Action<Task, object>
作为参数,然后将任何 object
值(传递给Action<Task, object>
的“状态”值)作为参数。 That state value has no effect whatsoever on what ContinueWith()
actually does. 该状态值对
ContinueWith()
实际作用没有任何影响。 It just passes that value to your delegate. 它只是将该值传递给您的代表。
If you want to use the TaskContinuationOptions.OnlyOnFaulted
value to actually control the behavior of the ContinueWith()
method, you need to use an overload that includes that parameter type specifically. 如果要使用
TaskContinuationOptions.OnlyOnFaulted
值实际控制ContinueWith()
方法的行为,则需要使用专门包含该参数类型的重载。
The easiest way to fix your code would be to simply pass null
as the state value for the ContinueWith(Action<Task, object>, object, TaskContinuationOptions)
overload: 修复代码的最简单方法是简单地将
null
作为状态值传递给ContinueWith(Action<Task, object>, object, TaskContinuationOptions)
重载:
var task = Task.Factory
.StartNew(() => { Console.WriteLine("Hello world!"); })
.ContinueWith((x, y) =>
{
Console.WriteLine("This should not get printed!");
}, null, TaskContinuationOptions.OnlyOnFaulted);
Do note that in this case, your task
object will get canceled after the first task finishes rather than executing the continuation (by design, of course). 请注意,在这种情况下,您的
task
对象将在第一个任务完成后取消,而不是执行继续操作(当然是设计使然)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.