TaskContinuationOptions 组合

TaskContinuationOptions combinations

当我查看异步模式时 PipeTo for Akka.NET 我发现了作者使用 TaskContinuationOptions 和运算符 & 的例子。这是一个错误,还是将“&”与 Akka.NET 和 PipeTo 一起使用是一种正确的方式?

为了更好的解释: AttachedToParent & ExecuteSynchronously 给出 0,内部 lambda 将作为异步任务调用。

TaskContinuationOptions.cs

/// When no continuation options are specified, specifies that default behavior should be used when executing a continuation. The continuation runs asynchronously when the antecedent task completes, regardless of the antecedent's final property value. It the continuation is a child task, it is created as a detached nested task.

None = 0,
AttachedToParent = 4,
ExecuteSynchronously = 524288, // 0x00080000

问题应该是“&”或“|”运算符?

TL;DR:

是的。作者应该使用 | 而不是 &.

长答案:

按位与 => 只有当比较的两个位都为 1 时,结果位才为 1。
按位或 => 如果两个比较位中的任何一个为 1,则结果位为 1。

所以你首先要将数字转换为二进制(我将添加一些 0 以便比较更容易):

  • 000000 : 00000000000000000000 (None)
  • 000001 : 00000000000000000001 (PreferFairness)
  • 000002 : 00000000000000000010 (LongRunning)
  • 000004 : 00000000000000000100 (AttachedToParent)
  • 065536 : 00010000000000000000 (NotOnRanToCompletion)
  • 131072 : 00100000000000000000 (NotOnFaulted)
  • 196608 : 00110000000000000000 (OnlyOnCanceled)
  • 262144 : 01000000000000000000 (NotOnCanceled)
  • 327680 : 01010000000000000000 (OnlyOnFaulted)
  • 393216 : 01100000000000000000 (OnlyOnFaulted)
  • 524288 : 10000000000000000000 (ExecuteSynchronously)

现在你知道了,例如,OnlyOnCanceled 等同于 NotOnFaulted+ NotOnRanToCompletion
或者,使用按位运算符:NotOnFaulted | NotOnRanToCompletion

另一方面 NotOnFaulted & NotOnRanToCompletion 等于 0,对应于 None.
OnlyOnCanceled & NotOnFaulted == NotOnRanToCompletion.

所以答案是:当你想合并时,使用|。当你想获得差异时,使用 &.

我希望这个例子更清楚。