好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C# ManualResetEvent使用方法详解

本文实例为大家分享了manualresetevent的使用方法,供大家参考,具体内容如下

1. 源码下载:

下载地址: manualresetevent

demo:

2. 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;

 

namespace manualreseteventdemo

{

  class mredemo

  {

   private manualresetevent _mre;

 

   public mredemo()

   {

    this ._mre = new manualresetevent( true );

   }

 

   public void createthreads()

   {

    thread t1 = new thread( new threadstart(run));

    t1.start();

 

    thread t2 = new thread( new threadstart(run));

    t2.start();

   }

 

   public void set ()

   {

    this ._mre. set ();

   }

 

   public void reset()

   {

    this ._mre.reset();

   }

 

   private void run()

   {

    string strthreadid = string .empty;

    try

    {

     while ( true )

     {

      // 阻塞当前线程

      this ._mre.waitone();

 

      strthreadid = thread.currentthread.managedthreadid.tostring();

      console.writeline( "thread(" + strthreadid + ") is running..." );

 

      thread.sleep(5000);

     }

    }

    catch (exception ex)

    {

     console.writeline( "线程(" + strthreadid + ")发生异常!错误描述:" + ex.message.tostring());

    }

   }

 

  }

}

?

using system;

using system.collections.generic;

using system.linq;

using system.text;

 

namespace manualreseteventdemo

{

  class program

  {

   static void main( string [] args)

   {

    console.writeline( "****************************" );

    console.writeline( "输入\"stop\"停止线程运行..." );

    console.writeline( "输入\"run\"开启线程运行..." );

    console.writeline( "****************************\r\n" );

 

    mredemo objmre = new mredemo();

    objmre.createthreads();

 

    while ( true )

    {

     string input = console.readline();

     if (input.trim().tolower() == "stop" )

     {

      console.writeline( "线程已停止运行..." );

      objmre.reset();

     }

     else if (input.trim().tolower() == "run" )

     {

      console.writeline( "线程开启运行..." );

      objmre. set ();

     }

    }

    

   }

  }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

dy("nrwz");

查看更多关于C# ManualResetEvent使用方法详解的详细内容...

  阅读:40次