How to estimate method execution time?

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

提交回复
热议问题