• ManualResetEvent使用Demo


    ManualResetEvent使用演示

    ManualResetEvent 允许线程通过发信号互相通信。通常,此通信涉及一个线程在其他线程进行之前必须完成的任务。
    当一个线程开始一个活动(此活动必须完成后,其他线程才能开始)时,它调用 Reset 以将 ManualResetEvent 置于非终止状态。此线程可被视为控制 ManualResetEvent。调用 ManualResetEvent 上的 WaitOne 的线程将阻止,并等待信号。当控制线程完成活动时,它调用 Set 以发出等待线程可以继续进行的信号。并释放所有等待线程。
    一旦它被终止,ManualResetEvent 将保持终止状态(即对 WaitOne 的调用的线程将立即返回,并不阻塞),直到它被手动重置。
    可以通过将布尔值传递给构造函数来控制 ManualResetEvent 的初始状态,如果初始状态处于终止状态,为 true;否则为 false。

    public class EventClient : Form
    {
        
    private Button CreateThreas;
        
    private ManualResetEvent m_Event1;
        
    private Button Signal;
        
    private Button Reset;


        
    public EventClient()
        {
            InitializeComponent();
            m_Event1 
    = new ManualResetEvent(false);
        }

        
    private void InitializeComponent()
        {
            
    // 
        }
        
        [STAThread]
        
    static void Main() 
        {
            Application.Run(
    new EventClient());
        }

        
    // 创建线程
        private void OnCreateThreads(object sender,EventArgs e)
        {
            ThreadStart threadStart 
    = new ThreadStart(Start);
            Thread thread1 
    = new Thread(threadStart);            
            thread1.Start();

            Thread thread2 
    = new Thread(threadStart);            
            thread2.Start();

        }

        
    // 线程执行体
        protected void Start()
        {
            
    // 阻塞当前线程线程
            m_Event1.WaitOne();
            
            
    int threadID = Thread.CurrentThread.GetHashCode();
            
    string caption = "Thread ID = " + threadID;
            MessageBox.Show(
    "Stopped Waiting",caption); 
        }

        
    private void OnSignal(object sender,EventArgs e)
        {
            
    // 通知被m_Event1阻塞的线程继续执行
            
    // 这里是thread1, thread2
            m_Event1.Set();
        }

        
    private void OnReset(object sender,EventArgs e)
        {
            m_Event1.Reset();
        }
    }
  • 相关阅读:
    技术总监7年经验——论程序员的职业发展路线
    2.MySQL入门基本操作初体验
    1.MySQL的安装(linux Ubuntu环境下)
    Boot Petalinux Project Using a remote system
    字符设备驱动、平台设备驱动、设备驱动模型、sysfs的比较和关联
    linux采用模块方法,添加一个新的设备
    在远程服务器上完成本地设备的程序烧写和调试(基于vivado ,SDK软件)
    Linux Master/Baremetal Remote 配置下的裸机调试
    利用Xlinix SDK 建立Linux程序以及对该程序进行调试
    Vivado Launching SDK "Importing Hardware Specification" error的解决方法
  • 原文地址:https://www.cnblogs.com/hcfalan/p/505217.html
Copyright © 2020-2023  润新知