This question was answered by Joe Hoag on the Parallel Team blog in 2011: Creating a task. TimeoutAfter Method .
The solution uses the TaskCompletionSource object and includes several optimizations (12%, just avoiding captures), handles cleaning and covers extreme cases, such as calling TimeoutAfter, when the target task is already completed, sending invalid timeouts, etc.
The beauty of Task.TimeoutAfter is that it is very easy to put it together with other extensions, because it does only one thing: it notifies you that the timeout has expired. He is not trying to cancel your task. You decide what to do when a TimeoutException is thrown.
A brief implementation using Stephen async/await 's async/await also provided, although cross cases are also not covered.
Optimized implementation:
public static Task TimeoutAfter(this Task task, int millisecondsTimeout) {
and Stephen Toub, without checks for edge cases:
public static async Task TimeoutAfter(this Task task, int millisecondsTimeout) { if (task == await Task.WhenAny(task, Task.Delay(millisecondsTimeout))) await task; else throw new TimeoutException(); }
Panagiotis kanavos
source share