How to estimate method execution time?

前端 未结 3 1382
夕颜
夕颜 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: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

提交回复
热议问题