How to estimate method execution time?

前端 未结 3 1378
夕颜
夕颜 2021-02-10 15:31

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 mechanis

相关标签:
3条回答
  • 2021-02-10 16:14

    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);
       } 
    
    0 讨论(0)
  • 2021-02-10 16:16

    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

    0 讨论(0)
  • 2021-02-10 16:34

    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 讨论(0)
提交回复
热议问题