C#多线程开始、暂停、恢复简单例子

 

C#多线程开始、暂停、恢复简单例子


namespace Test
{ 
    
    public partial class Form4 : Form
    {
        public Form4()
        {
            InitializeComponent();
            Label.CheckForIllegalCrossThreadCalls = false;
        }
        Thread thread;
        ManualResetEvent ma;
        bool on_off = false;
        bool stop = false;

        private void button1_Click(object sender, EventArgs e)
        {
            thread = new Thread(Runtime);
            thread.Start();
        }


        void Runtime()
        {
            for (int i = 1; i <= 100; i++)
            {
                if (stop)
                    return;
                if (on_off)
                {
                    ma = new ManualResetEvent(false);
                    ma.WaitOne();
                }
                textBox1.AppendText("计时 :" + i + "\r\n");
                Thread.Sleep(100);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            on_off = true;
            textBox1.AppendText("暂停中 :\r\n");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            on_off = false;
            ma.Set();
            textBox1.AppendText("继续计时 :\r\n");
        }

        private void button4_Click(object sender, EventArgs e)
        {
            stop = true;
            textBox1.AppendText("停止计时 \r\n");
        }
    }
}