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