ThreadPoolGuardian, kills of zombie processes that run for too long.
public static class ThreadPoolGuardian | |
{ | |
private static readonly BlockingCollection<Guard> guards = new BlockingCollection<Guard>(); | |
public static void Queue(Action action) | |
{ | |
Action wrapper = () => | |
{ | |
var guard = new Guard | |
{ | |
IsDone = false, | |
Thread = Thread.CurrentThread, | |
Timeout = DateTime.Now.AddSeconds(5), | |
}; | |
Guard(guard); | |
action(); | |
guard.IsDone = true; | |
}; | |
ThreadPool.UnsafeQueueUserWorkItem(_ => wrapper(), null); | |
} | |
static ThreadPoolGuardian() | |
{ | |
var t = new Thread(() => | |
{ | |
foreach(var guard in guards.GetConsumingEnumerable()) | |
{ | |
if (guard.IsDone) | |
continue; | |
if (guard.Timeout >= DateTime.Now) | |
{ | |
TimeSpan delay = guard.Timeout - DateTime.Now; | |
if (delay.Milliseconds > 0) //could possibly occur | |
Thread.Sleep(delay); | |
} | |
if (!guard.IsDone) | |
{ | |
Console.WriteLine("Killing thread " + guard.Thread.GetHashCode()); | |
guard.Thread.Abort(); | |
} | |
} | |
Console.WriteLine("exit"); | |
}) | |
{ | |
IsBackground = true | |
}; | |
t.Start(); | |
} | |
internal static void Guard(Guard guard) | |
{ | |
guards.Add(guard); | |
} | |
} | |
public class Guard | |
{ | |
public volatile bool IsDone; | |
public Thread Thread; | |
public DateTime Timeout; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment