开发者

How to estimate method execution time?

I have requirement to cancel method execution if it takes the more than two seconds to complete 开发者_StackOverflowand restart it on another thread.

So, is there any way/call back mechanism/HACK, I can make method inform me that it crossed 2 seconds time limit?


check if network drive exists with timeout in c#
https://web.archive.org/web/20140222210133/http://kossovsky.net/index.php/2009/07/csharp-how-to-limit-method-execution-time

Async Pattern:

public static T SafeLimex<T>(Func<T> F, int Timeout, out bool Completed)   
   {
       var iar = F.BeginInvoke(null, new object());
       if (iar.AsyncWaitHandle.WaitOne(Timeout))
       {
           Completed = true;
           return F.EndInvoke(iar);
       }
         F.EndInvoke(iar); //not calling EndInvoke will result in a memory leak
         Completed = false;
       return default(T);
   } 


You should create System.Threading.Timer on two seconds, and run your method in another thread and wait for callback from it, if method completes before timer runs you should dispose timer, otherwise you should abort thread in which you method are executing. This is pretty simple for example

using (new Timer(BreakFunction, true, TimeSpan.FromMinutes(2), Timeout.Infinite))
                    {
                        //TODO:here you should create another thread that will run your method
                    }

In BreakFunction you should abort thread that runs your methods


It would be good if you can find it. I've been looking for it too.

What I usually do is start the method in another Thread, and start a Timer with 2 seconds in this case. The first time it raises the event, just do:

if (a.IsAlive)
{
   a.Abort();
}

Two important things:

  • The Thread declared should be visible by the method that handles the timer
  • When calling Abort(), it raises ThreadAbortException, so you should correctly handle it in the method.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜