How to abort a long running method?

后端 未结 5 1323
攒了一身酷
攒了一身酷 2021-01-23 01:23

I have a long running method and I want to add timeout into it. Is it feasible to do that? Something like:

AbortWaitSeconds(20)
{
    this.LongRunningMethod();
}         


        
5条回答
  •  没有蜡笔的小新
    2021-01-23 01:53

    Since you have no control over that code I believe the correct approach would be to run that code using WaitHandles and the ThreadPool:

    WaitHandle waitHandle = new AutoResetEvent(false);
    ThreadPool.QueueUserWorkItem(new WaitCallback(), waitHandle);
    WaitHandle.WaitAll(new[]{ waitHandle }, );
    

    Here you can find more info on how WaitHandle works.

提交回复
热议问题