Skip to content

Instantly share code, notes, and snippets.

@devlights
Created July 8, 2016 09:51
Show Gist options
  • Select an option

  • Save devlights/0cac7df87ed1ae28722999b1feea1ab3 to your computer and use it in GitHub Desktop.

Select an option

Save devlights/0cac7df87ed1ae28722999b1feea1ab3 to your computer and use it in GitHub Desktop.
Task.WhenAllを利用している場合のタイムアウト処理の書き方 (Task.WhenAll, Task.WhenAny, Task.Delay)
var t1Result = 0;
var t2Result = 0;
var t1 = Task.Run(() =>
{
Thread.Sleep(TimeSpan.FromSeconds(1));
Interlocked.Increment(ref t1Result);
});
var t2 = Task.Run(() =>
{
Thread.Sleep(TimeSpan.FromSeconds(3));
Interlocked.Increment(ref t2Result);
});
var tasks = Task.WhenAll(t1, t2);
var timeout = Task.Delay(TimeSpan.FromSeconds(2));
// 処理が完了するか、タイムアウトするまで待つ
await Task.WhenAny(tasks, timeout);
if (t1Result == 1 && t2Result == 1)
{
"処理完了".Dump();
}
else
{
"タイムアウト".Dump();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment