1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| public sealed class Watchdog : IDisposable
{
private Thread _monitorThread;
private Thread _threadToWatch;
private EventWaitHandle _waitHandle;
public Watchdog()
{
_threadToWatch = Thread.Current;
_waitHandle = new ManualResetEvent(false);
_monitorThread = new Thread(Run);
_monitorThread.Background = true;
_monitorThread.Start();
}
// Attend jusqu'à 10mins puis avorte threadToWatch si différent de null
private void Run()
{
_waitHandle.WaitOne(10 * 60 * 1000, false);
// Avortement du thread si cette instance n'a pas été disposée proprement
// Copie locale de threadToWatch en cas de chgt de thread entre le test et abort
var threadToAbort = _threadToWatch;
if (threadToAbort != null) threadToAbort.Abort();
}
// Appelé quand tout s'est bien passé.
public void Dispose()
{
// threadToWatch n'a pas bogué, pas besoin de l'avorter.
_threadToWatch = null;
// Réveil de monitorThread qui va se terminer en silence.
_waitHandle.Set();
}
} |
Partager