Last active
August 29, 2015 14:27
-
-
Save kwal/f377f97599ca3988e54a to your computer and use it in GitHub Desktop.
Task Timeout
This file contains 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 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