Skip to content

Instantly share code, notes, and snippets.

@musoftware
Last active August 29, 2015 14:08
Show Gist options
  • Save musoftware/0ce78a40cd1860c8bda5 to your computer and use it in GitHub Desktop.
Save musoftware/0ce78a40cd1860c8bda5 to your computer and use it in GitHub Desktop.
Best way to Make Thread.sleep replacement without hang
//Install PM> Install-Package Microsoft.Bcl.Async
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class ExTask : Task
{
public ExTask(Action action)
: base(action)
{ }
public static Task Delay(double milliseconds)
{
var tcs = new TaskCompletionSource<bool>();
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += (obj, args) =>
{
tcs.TrySetResult(true);
};
timer.Interval = milliseconds;
timer.AutoReset = false;
timer.Start();
return tcs.Task;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment