Timed Operation

by ipsit 12. March 2009 10:49

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;

}           

}       

}

}

Till then Happy Coding.

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

General

Comments are closed

Inida

About Coderslog

One fine day we thought, we need to be contributing to our community.

So good sense prevailed, and that's how coderslog got started. That's about us.

Calendar

<<  March 2010  >>
MoTuWeThFrSaSu
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar

RecentPosts

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010 CodersLog