Last active
August 29, 2015 14:16
-
-
Save zgramana/50a51fd41b5a3f5e848e to your computer and use it in GitHub Desktop.
Task.Delay backport
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
using System; | |
using System.Threading.Tasks; | |
using System.Threading; | |
namespace Couchbase.Lite.Shared | |
{ | |
public static class TaskExtensions | |
{ | |
static int CheckTimeout (TimeSpan timeout) | |
{ | |
try { | |
return checked ((int)timeout.TotalMilliseconds); | |
} catch (System.OverflowException) { | |
throw new ArgumentOutOfRangeException ("timeout"); | |
} | |
} | |
public static Task Delay (int millisecondsDelay) | |
{ | |
return Delay (millisecondsDelay, CancellationToken.None); | |
} | |
public static Task Delay (TimeSpan delay) | |
{ | |
return Delay (CheckTimeout (delay), CancellationToken.None); | |
} | |
public static Task Delay (TimeSpan delay, CancellationToken cancellationToken) | |
{ | |
return Delay (CheckTimeout (delay), cancellationToken); | |
} | |
public static Task Delay (int millisecondsDelay, CancellationToken cancellationToken) | |
{ | |
if (millisecondsDelay < -1) | |
throw new ArgumentOutOfRangeException ("millisecondsDelay"); | |
var tcs = new TaskCompletionSource<bool>(); | |
if (cancellationToken.IsCancellationRequested) | |
{ | |
tcs.SetCanceled(); | |
return tcs.Task; | |
} | |
// var task = new Task (TaskActionInvoker.Empty, null, cancellationToken, TaskCreationOptions.None, null, null); | |
// task.SetupScheduler (TaskScheduler.Default); | |
var task = tcs.Task; | |
if (millisecondsDelay != Timeout.Infinite) { | |
var timer = new Timer (delegate (object state) { | |
var t = (Task) state; | |
// if (t.Status == TaskStatus.WaitingForActivation) { | |
// t.Status = TaskStatus.Running; | |
// } | |
tcs.SetResult(true); | |
}, task, millisecondsDelay, -1); | |
// | |
task.ContinueWith ((t) => timer.Dispose()); | |
} | |
return task; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment