Skip to content

Instantly share code, notes, and snippets.

@in-async
Last active October 15, 2023 04:39
Show Gist options
  • Save in-async/25d7f2195c0c07ddf445fcff3269f0e6 to your computer and use it in GitHub Desktop.
Save in-async/25d7f2195c0c07ddf445fcff3269f0e6 to your computer and use it in GitHub Desktop.
どっちも同じように OperationCanceledException を投げてるだけなのに、 Task.Status が異なるのなーんでだ
CancellationToken ct = new CancellationTokenSource(0).Token;
Task task1 = Task.Run(() => throw new OperationCanceledException(ct));
Task task2 = Task.Run(() => ct.ThrowIfCancellationRequested());
Task.WhenAll(task1, task2).ContinueWith(_ => {
task1.Status.Dump(); // Canceled
task2.Status.Dump(); // Faulted
});
@in-async
Copy link
Author

教訓

Task.Run(...) を使う際は、どのオーバーロードを使用しているか意識する事。

Task.Run(...) には似たようなオーバーロードが多く、呼び間違えやすいので、注意する必要がある。

@in-async
Copy link
Author

そもそも

Task.Run(() => throw new OperationCanceledException(ct));

Task.Run(Func<Task>) にオーバーロード解決されてるのが直感的におかしいんだけどな。仕様らしい。

ref.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment