Created
December 9, 2011 13:39
-
-
Save biac/1451573 to your computer and use it in GitHub Desktop.
LongTimeMethod() キャンセル可能バージョン
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static int LongTimeMethod(int n, CancellationToken token) | |
{ | |
// このロジックは、処理に長い長~い時間が掛かるのだと思ってくれ。 | |
Thread.Sleep(1000); | |
// 非同期実行中のキャンセルを実現するには、ロジックも改造する必要がある。 | |
if (token.IsCancellationRequested) | |
{ | |
token.ThrowIfCancellationRequested(); | |
// return -1; などとリターンすることも可能だが、それをやってしまうと、 | |
// 呼び出し元では Cancel() したのに値が取得できたという、 | |
// 矛盾した結果を受け取り、悩むことになる。 | |
} | |
Thread.Sleep(2000); | |
return n * 2; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment