ManualResetEvent在线程里简单应用

来源:互联网 发布:手绘软件下载mac 编辑:程序博客网 时间:2024/06/03 14:38

        在C#开发过程中,需要用线程来处理比较复杂的逻辑,用Thread自身的相关函数比如Suspend(),Resume()等函数有时不能满足需求。使用ManualResetEvent比较简单实现Suspend(),Resume()等函数的功能。

     实现代码大体如下:

     Thread thread = null;//线程的声明

     ManualResetEvent manualEvent = new ManualResetEvent(true); //定义 初始状态为true,说明一开始有信号

    //线程运行的处理函数

    public void Run()
     {
            int cur_id = 0;
            for (int id = 0; id < Id_list.Count; id++)
            {
                 manualEvent.WaitOne();
                 //...逻辑的处理
           
                Thread.Sleep(1000);
              
            }
       }

  //启动一个线程

 thread = new Thread(new ThreadStart(Run));
 thread.Start();


//暂停一个线程的运行 Event没有信号,WaitOne()一直在等。

manualEvent.Reset();


//重让线程运行 Event有信号,WaitOne()收到信号向下执行。

manualEvent.Set();


//结束线程

if (thread != null)
      thread.Abort();

 

至此ManualResetEvent在线程中简单应用完成。

 

参考:

https://msdn.microsoft.com/zh-cn/library/system.threading.manualresetevent.aspx

 

  

 

0 0
原创粉丝点击