How to abort a long running method?

后端 未结 5 1354
攒了一身酷
攒了一身酷 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 02:10

    try this

    class Program
    {
        static void Main(string[] args)
        {
            if (RunWithTimeout(LongRunningOperation, TimeSpan.FromMilliseconds(3000)))
            {
                Console.WriteLine("Worker thread finished.");
            }
            else
            {
                Console.WriteLine("Worker thread was aborted.");
            }
        }
    
        static bool RunWithTimeout(ThreadStart threadStart, TimeSpan timeout)
        {
            Thread workerThread = new Thread(threadStart);
    
            workerThread.Start();
    
            bool finished = workerThread.Join(timeout);
            if (!finished)
                workerThread.Abort();
    
            return finished;
        }
    
        static void LongRunningOperation()
        {
            Thread.Sleep(5000);
        }
    }
    

    you can see it

提交回复
热议问题