c#信号量实现线程挂起,暂停,继续,停止操作

c#信号量实现线程挂起,暂停,继续,停止操作

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace testManualResetEvent
{

    public partial class Form1 : Form
    {
        ManualResetEvent manualResetEvent = new ManualResetEvent(false);//初始信号量状态false,线程启动后为阻塞状态
        CancellationTokenSource cts = new CancellationTokenSource();//终止线程
        Task task;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            task = new Task(run, cts.Token);
            task.Start();
        }

        bool flagwait = false;
        private void run()
        {
            int i = 0;
            while (true)
            {
                if (flagwait)
                {
                    #region
                    /* 
                     * WaiOne函数会暂停当前线程
                     * 继续条件有两个:
                     * 1、参数1指定的时间到了,如:5000ms(此时忽略信号量状态)
                     * 2、信号量变为置位状态。
                     * 
                     * 如果调用WaiOne的无参函数,则无限等待,继续条件为:
                     * 信号量变为置位状态。
                     */
                    #endregion

                    manualResetEvent.Reset();//先复位信号量(信号量置位情况下,未复位无法阻塞线程)
                    bool flag = manualResetEvent.WaitOne(1000, false);//不指定时间则无限暂停

                    flagwait = false;
                }

                
                manualResetEvent.WaitOne();//不指定时间则无限暂停

                this.Invoke(new Action<string>((s) => { label1.Text = s; }), i++.ToString());

                #region 线程终止CancellationTokenSource
                if (cts.Token.IsCancellationRequested)
                {
                    Console.WriteLine("线程被终止!");
                    break;
                }
                #endregion


                Thread.Sleep(1);
            }
        }

        private void button_阻塞线程_Click(object sender, EventArgs e)
        {
            flagwait = true;
        }

        private void button_信号量置位_Click(object sender, EventArgs e)
        {
            manualResetEvent.Set();
        }

        private void button_信号量复位_Click(object sender, EventArgs e)
        {
            manualResetEvent.Reset();
        }

        private void button_CancellationTokenSource终止线程_Click(object sender, EventArgs e)
        {
            cts.Token.ThrowIfCancellationRequested();
            cts.Cancel();
        }
    }
}

 

posted @ 2021-09-07 14:21  txwtech  阅读(993)  评论(1编辑  收藏  举报