Created
July 8, 2016 09:51
-
-
Save devlights/0cac7df87ed1ae28722999b1feea1ab3 to your computer and use it in GitHub Desktop.
Task.WhenAllを利用している場合のタイムアウト処理の書き方 (Task.WhenAll, Task.WhenAny, Task.Delay)
This file contains hidden or 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
| 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