Skip to content

Instantly share code, notes, and snippets.

@derekantrican
Last active July 28, 2020 03:30
Show Gist options
  • Save derekantrican/dd358184c3ea8d26ba1cef70d31dda36 to your computer and use it in GitHub Desktop.
Save derekantrican/dd358184c3ea8d26ba1cef70d31dda36 to your computer and use it in GitHub Desktop.
Add a timeout to any section of C# code
using System.Threading;
//USAGE:
//using (Timeout timeout = new Timeout(TimeSpan.FromSeconds(5), "This code timed out!"))
//{
// SomeLinesOfCodeThatYouWantToCheck...
//}
public class Timeout: IDisposable
{
private Thread timeoutThread;
public Timeout(TimeSpan timeoutDuration, string message = null)
{
timeoutThread = new Thread(() =>
{
Thread.Sleep(timeoutDuration);
throw new Exception(message ?? "Timeout reached");
});
timeoutThread.Start();
}
public void Dispose()
{
timeoutThread.Abort();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment