Skip to content

Instantly share code, notes, and snippets.

@kwal
Last active August 29, 2015 14:27
Show Gist options
  • Save kwal/f377f97599ca3988e54a to your computer and use it in GitHub Desktop.
Save kwal/f377f97599ca3988e54a to your computer and use it in GitHub Desktop.
Task Timeout
var cutoff = 30000;
using (var delayCancellation = new CancellationTokenSource())
{
var mainTask = Task.Run(() =>
{
// Whatever needs doing...
});
var delayTask = Task.Delay(cutoff, delayCancellation.Token).ContinueWith(async t =>
{
// Continue to wait for task to complete and do something else with the result
var result = await mainTask;
}, TaskContinuationOptions.NotOnCanceled);
if (await Task.WhenAny(mainTask, delayTask) == mainTask)
{
// Task completed before cutoff
delayCancellation.Cancel();
var result = await mainTask; // re-await in case of fault/exception to allow for rethrow
}
else
{
// Task did not complete before cutoff - inform user, write to log, etc.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment