Freigeben über


Task-based Asynchronous Pattern - WithTimeout

The same way we in CCR sometimes wanted to add a timeout to an existing "task" you probably want to do the same in TAP. So here are two extension methods you could use to add a timeout to any task of your choice:

  1: public async static Task WithTimeout(this Task task, TimeSpan timeout)
 2: {
 3:     var cancelationSource = new CancellationTokenSource();
 4:     var delay = Task.Delay(timeout, cancelationSource.Token);
 5:     await Task.WhenAny(task, delay);
 6:     if (task.IsCompleted)
 7:     {
 8:         cancelationSource.Cancel();
 9:     }
 10:     else
 11:     {
 12:         throw new TimeoutException();
 13:     }
 14: }
 15:         
 16: public async static Task<T> WithTimeout<T>(this Task<T> task, TimeSpan timeout)
 17: {
 18:     await ((Task)task).WithTimeout(timeout);
 19:     return await task;
 20: }

Comments

  • Anonymous
    September 08, 2012
    Don't timeouts normally stop the asynchronous operation, so these extension methods are only 'ad-hoc' in that they wait for a set period of time?

  • Anonymous
    September 09, 2012
    The comment has been removed