Skip to content

Instantly share code, notes, and snippets.

@biac
Created December 9, 2011 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save biac/1451573 to your computer and use it in GitHub Desktop.
Save biac/1451573 to your computer and use it in GitHub Desktop.
LongTimeMethod() キャンセル可能バージョン
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