How to abort a long running method?

后端 未结 5 1244
攒了一身酷
攒了一身酷 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:58

    You can only abort long running process from the same thread if you have a code point in which to introduce a check and exit. This is because - clearly - the thread is busy, so it can't process checks to abort itself. So, your example which only contains one call to 'LongRunningMethod' could not be aborted from the same thread. You'd need to show more code in order to get direction on that.

    As a general rule, long-running tasks are best sent to different threads (e.g; via a BackgroundWorker or new Thread) so they can be aborted.

    Here is a simple way to do this;

    private void StartThread()
    {
        Thread t = new Thread(LongRunningMethod);
        t.Start();
        if (!t.Join(10000)) // give the operation 10s to complete
        {
            // the thread did not complete on its own, so we will abort it now
            t.Abort();
        }
    }
    
    private void LongRunningMethod()
    {
        // do something that'll take awhile
    }
    

提交回复
热议问题