Skip to content

Instantly share code, notes, and snippets.

@thomaslevesque
Created May 14, 2014 08:23
Show Gist options
  • Save thomaslevesque/5d006546bdddac7e341f to your computer and use it in GitHub Desktop.
Save thomaslevesque/5d006546bdddac7e341f to your computer and use it in GitHub Desktop.
A cancellable synchronous Sleep implementation
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();
}
}
}
@thomaslevesque
Copy link
Author

  • Thread.Sleep doesn't accept a CancellationToken, so it can't be interrupted
  • Task.Delay accepts a CancellationToken, but it's only available since .NET 4.5, and it's asynchronous, which is not always practical

Sleeper.Sleep combines the features of those two methods: it is synchronous and cancellable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment