How to estimate method execution time?

烂漫一生 提交于 2019-12-03 09:12:45
Aseem Gautam

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