Created
May 14, 2014 08:23
-
-
Save thomaslevesque/5d006546bdddac7e341f to your computer and use it in GitHub Desktop.
A cancellable synchronous Sleep implementation
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; | |
namespace Utils.Threading | |
{ | |
/// <summary> | |
/// A cancellable replacement for Thread.Sleep | |
/// </summary> | |
public static class Sleeper | |
{ | |
public static void Sleep(int millisecondsTimeout, CancellationToken cancellationToken = default(CancellationToken)) | |
{ | |
Sleep(TimeSpan.FromMilliseconds(millisecondsTimeout), cancellationToken); | |
} | |
public static void Sleep(TimeSpan timeout, CancellationToken cancellationToken = default(CancellationToken)) | |
{ | |
var mre = new ManualResetEvent(false); | |
var registration = default(CancellationTokenRegistration); | |
if (cancellationToken.CanBeCanceled) | |
registration = cancellationToken.Register(() => mre.Set()); | |
mre.WaitOne(timeout); | |
registration.Dispose(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thread.Sleep
doesn't accept aCancellationToken
, so it can't be interruptedTask.Delay
accepts aCancellationToken
, but it's only available since .NET 4.5, and it's asynchronous, which is not always practicalSleeper.Sleep
combines the features of those two methods: it is synchronous and cancellable.