How to estimate method execution time?

偶尔善良 提交于 2019-12-04 14:26:11

问题


I have requirement to cancel method execution if it takes the more than two seconds to complete and 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?


回答1:


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);
   } 



回答2:


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




回答3:


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.


来源:https://stackoverflow.com/questions/5025509/how-to-estimate-method-execution-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!