How to limit the execution time of a function in c sharp?

后端 未结 8 826
太阳男子
太阳男子 2020-12-30 03:13

I\'ve got a problem. I\'m writing a benchmark and I have a function than is either done in 2 seconds or after ~5 minutes(depending on the input data). And I would like to st

8条回答
  •  猫巷女王i
    2020-12-30 03:53

    The best way would be that your function can check its execution time often enough to decide to stop it it takes too long.

    If this is not the case, then run the function in a separate thread. In your main thread start a 3 seconds timer. When timer elapses, kill the separate thread using Thread.Abort() (of course unless the function is already over). See sample code and preacuations of usage in the function docs.

提交回复
热议问题