public static object Invoke(
TimeSpan time,
Delegate method,
CompensatingDelegate compensationMethod,
params object[] parameters
){
if (method == null) throw new ArgumentNullException("method");
if (time.TotalSeconds <= 0) throw new ArgumentOutOfRangeException("time");
var timeBoxedOperation = new Operation();
timeBoxedOperation.Method = method;
timeBoxedOperation.Parameters = parameters;
var thread = new Thread(new ThreadStart(timeBoxedOperation.Run));
thread.IsBackground = true;
thread.Start();
if (!thread.Join(time)){
if (compensationMethod != null)
compensationMethod();
if (timeBoxedOperation.Exception != null)
throw timeBoxedOperation.Exception;
return null;
}
if (timeBoxedOperation.Exception != null)throw timeBoxedOperation.Exception;
return timeBoxedOperation.Result;
}
private class Operation{
public volatile Delegate Method;
public volatile object[] Parameters;
public volatile Exception Exception;
public volatile object Result;
public void Run(){
try{
this.Result = Method.DynamicInvoke(Parameters);
}catch (ThreadAbortException ex){
this.Exception = ex;
}catch (Exception exc){
this.Exception = exc;
}
}
}