I tried to change my code as little as possible, but here is a working example that behaves the same as Task.Delay.
It is important to note that I use TrySetCanceled and TrySetResult , because the timer may end after the task is canceled. Ideally, you want to stop the timer.
Also note that a canceled task will raise a TaskCanceledException
static void Main(string[] args) { // A cancellation source that will cancel itself after 1 second var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(1)); try { // This will only wait 1 second because as it will be cancelled. Task t = Delay(5000, cancellationTokenSource.Token); t.Wait(); Console.WriteLine("The task completed"); } catch (AggregateException exception) { // Expecting a TaskCanceledException foreach (Exception ex in exception.InnerExceptions) Console.WriteLine("Exception: {0}", ex.Message); } Console.WriteLine("Done"); Console.ReadLine(); } private static Task Delay(int milliseconds, CancellationToken token) { var tcs = new TaskCompletionSource<object>(); token.Register(() => tcs.TrySetCanceled()); Timer timer = new Timer(_ => tcs.TrySetResult(null)); timer.Change(milliseconds, -1); return tcs.Task; }
Read a little more in your question. If you need Task.Delay and you are targeting .NET 4.0, then you should use the Microsoft Async nuget package from http://www.nuget.org/packages/Microsoft.Bcl.Async/ , which contains the TaskEx.Delay method
source share