Laden...

Timeout-Wächter

Erstellt von Haukinger vor 16 Jahren Letzter Beitrag vor 16 Jahren 3.045 Views
H
Haukinger Themenstarter:in
50 Beiträge seit 2007
vor 16 Jahren
Timeout-Wächter

Beschreibung:

Mit dieser Klasse kann man eine Zeitbegrenzung vorgeben, innerhalb derer ein Code-Block abgearbeitet sein muß. Wenn die Zeit abgelaufen ist, und der Code-Block ist nicht zu Ende, wird eine TimeoutException geworfen.


public class Guardian
{
  public delegate void Function();

  public static void Timeout( int seconds, Function function )
  {
    Exception innerException = null;
    System.Threading.Thread thread = new System.Threading.Thread( delegate()
    {
      try
      {
        function();
      }
      catch (System.Threading.ThreadAbortException)
      {
      }
      catch (Exception e)
      {
        innerException = e;
      }
    } );
    thread.Start();
    bool timedout = !thread.Join( seconds * 1000 );
    thread.Abort();
    thread.Join();
    if (innerException != null)
      throw innerException;
    if (timedout)
      throw new TimeoutException();
  }
}

Benutzung:


try
{
  Guardian.Timeout( 30, delegate
  {
    haengen_bleiben();
  } );
}
catch (TimeoutException e)
{
  reagieren();
}
catch (Exception e)
{
  andere_exceptions_fangen();
}

Das Snippet ist aus diesem Thread entstanden.

EDIT: Überflüssigen catch-Block entfernt.

Schlagwörter: Timeout