How to stop threads?

前端 未结 6 1030
清酒与你
清酒与你 2021-01-23 07:45

Hi guys I start threads with such code:

    Thread[] thr;
    private void button1_Click(object sender, EventArgs e)
    {
        decimal value = numericUpDown2         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-23 08:24

    If you want to know how to terminate the thread gracefully, I'd recommend you to take a look the following example on MSDN:

    using System;
    using System.Threading;
    
    public class Worker
    {
        public void DoWork()
        {
            while (!_shouldStop)
            {
                Console.WriteLine("worker thread: working...");
            }
            Console.WriteLine("worker thread: terminating gracefully.");
        }
        public void RequestStop()
        {
            _shouldStop = true;
        }
        // Volatile is used as hint to the compiler that this data
        // member will be accessed by multiple threads.
        private volatile bool _shouldStop;
    }
    
    public class WorkerThreadExample
    {
        static void Main()
        {
            Worker workerObject = new Worker();
            Thread workerThread = new Thread(workerObject.DoWork);
            workerThread.Start();
            Console.WriteLine("main thread: Starting worker thread...");
    
            while (!workerThread.IsAlive); // Loop until worker thread activates
    
            // Put the main thread to sleep for 1 millisecond to
            // allow the worker thread to do some work:
            Thread.Sleep(1);
    
            workerObject.RequestStop();
    
            // Use the Join method to block the current thread 
            // until the object's thread terminates.
            workerThread.Join();
            Console.WriteLine("main thread: Worker thread has terminated.");
        }
    }
    

提交回复
热议问题