Last active
July 28, 2020 03:30
-
-
Save derekantrican/dd358184c3ea8d26ba1cef70d31dda36 to your computer and use it in GitHub Desktop.
Add a timeout to any section of C# code
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.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