Learn.Develop.Share

Twitter












Time Boxed Method

I was looking for a Timed Method Implementation, which could notify me if the method is taking more than the stipulated time. I found an excellent  article by Stephen Toub at http://msdn.microsoft.com/en-us/magazine/cc163768.aspxJust modified it a bit. Please find it below. Do go to the link and read it, it’s a good read.    

public delegate void CompensatingDelegate();    

public class TimedOperaton    {       

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;

}           

}       

}

}



Feedback

No comments posted yet.