• ManualResetEvent 用法


    第一、简单介绍

        ManualResetEvent 允许线程通过发信号互相通信。通常,此通信涉及一个线程在其他线程进行之前必须完成的任务。当一个线程开始一个活动(此活动必须完成后,其他线程才能开始)时,它调用 Reset 以将 ManualResetEvent 置于非终止状态,此线程可被视为控制 ManualResetEvent。调用 ManualResetEvent 上的 WaitOne 的线程将阻止,并等待信号。

    当控制线程完成活动时,它调用 Set 以发出等待线程可以继续进行的信号。并释放所有等待线程。一旦它被终止,ManualResetEvent 将保持终止状态(即对 WaitOne 的调用的线程将立即返回,并不阻塞),直到它被手动重置。可以通过将布尔值传递给构造函数来控制 ManualResetEvent 的初始状态,

    如果初始状态处于终止状态,为 true;否则为 false。

    第二、代码演示

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication2
    {
        class MyThread
        {
            Thread t = null;
            ManualResetEvent manualEvent = new ManualResetEvent(true);//为trur,一开始就可以执行
            private void Run()
            {
                while (true)
                {
                    this.manualEvent.WaitOne();
                    Console.WriteLine("线程id:{0}", Thread.CurrentThread.ManagedThreadId);
                    Thread.Sleep(2000);
                }
            }
    
            public void Start()
            {
                this.manualEvent.Set();
            }
    
            public void Stop()
            {
                this.manualEvent.Reset();
            }
    
            public MyThread()
            {
                t = new Thread(this.Run);
                t.Start();
            }
    
        }
    
        class Program
        {     
            static void Main(string[] args)
            {
                MyThread myt = new MyThread();           
                while (true)
                {
                    Console.WriteLine("输入 stop 后台线程挂起 start 开始执行!");
                    string str = Console.ReadLine();
                    if (str.ToLower().Trim() == "stop")
                    {
                        Console.WriteLine("线程停止运行...
    ");
                        myt.Stop();
                    }
                    if (str.ToLower().Trim() == "start")
                    {
                        Console.WriteLine("线程开启运行...
    ");
                        myt.Start();
                    }
                }
            }
           
        }
    }
    

     运行测试结果

  • 相关阅读:
    【leetcode】1534. 统计好三元组
    【leetcode】1351. 统计有序矩阵中的负数
    【leetcode】1523. 在区间范围内统计奇数数目
    【leetcode】204. 计数质数
    【leetcode】993. 二叉树的堂兄弟节点
    【leetcode】1598. 文件夹操作日志搜集器
    【leetcode】1389. 按既定顺序创建目标数组
    【leetcode】增减字符串匹配
    【leetcode】1185.一周中的第几天
    052-158
  • 原文地址:https://www.cnblogs.com/clc2008/p/6905714.html
Copyright © 2020-2023  润新知