AutoResetEvent(Boolean) AutoResetEvent(Boolean) AutoResetEvent(Boolean) AutoResetEvent(Boolean) Constructor

Definición

Inicializa una nueva instancia de la clase AutoResetEvent con un valor booleano que indica si hay que establecer el estado inicial en señalado.Initializes a new instance of the AutoResetEvent class with a Boolean value indicating whether to set the initial state to signaled.

public:
 AutoResetEvent(bool initialState);
public AutoResetEvent (bool initialState);
new System.Threading.AutoResetEvent : bool -> System.Threading.AutoResetEvent
Public Sub New (initialState As Boolean)

Parámetros

initialState
Boolean Boolean Boolean Boolean

true para establecer el estado inicial en señalado; false para establecer el estado inicial en no señalado.true to set the initial state to signaled; false to set the initial state to non-signaled.

Ejemplos

En el ejemplo siguiente se usa un AutoResetEvent para sincronizar las actividades de dos subprocesos.The following example uses an AutoResetEvent to synchronize the activities of two threads. El primer subproceso, que es el subproceso de la aplicación, ejecuta Main.The first thread, which is the application thread, executes Main. Escribe valores en el recurso protegido, que es un static (Shared en Visual Basic) campo denominado number.It writes values to the protected resource, which is a static (Shared in Visual Basic) field named number. El segundo subproceso ejecuta estático ThreadProc método, que lee los valores escritos por Main.The second thread executes the static ThreadProc method, which reads the values written by Main.

El ThreadProc método espera a que el AutoResetEvent.The ThreadProc method waits for the AutoResetEvent. Cuando Main llamadas la Set método en el AutoResetEvent, el ThreadProc método lee un valor.When Main calls the Set method on the AutoResetEvent, the ThreadProc method reads one value. El AutoResetEvent lo restablece inmediatamente, por lo que el ThreadProc método espera de nuevo.The AutoResetEvent immediately resets, so the ThreadProc method waits again.

La lógica del programa garantiza que el ThreadProc método no leerá nunca el mismo valor dos veces.The program logic guarantees that the ThreadProc method will never read the same value two times. No garantiza que el ThreadProc método leerá cada valor escrito por Main.It does not guarantee that the ThreadProc method will read every value written by Main. Dicha garantía requeriría un segundo AutoResetEvent bloqueo.That guarantee would require a second AutoResetEvent lock.

Después de cada operación de escritura, Main produce mediante una llamada a la Thread.Sleep método, para dar al segundo subproceso una oportunidad de ejecutarse.After each write operation, Main yields by calling the Thread.Sleep method, to give the second thread a chance to execute. En caso contrario, en un equipo monoprocesador Main escribiría muchos valores entre las dos operaciones de lectura.Otherwise, on a single-processor computer Main would write many values between any two read operations.

using namespace System;
using namespace System::Threading;
ref class MyMainClass
{
public:
   static void MyReadThreadProc()
   {
      while ( true )
      {
         
         //The value will not be read until the writer has written
         // at least once since the last read.
         myResetEvent->WaitOne();
         Console::WriteLine( " {0} reading value: {1}", Thread::CurrentThread->Name, number );
      }
   }


   //Initially not signaled.
   static AutoResetEvent^ myResetEvent = gcnew AutoResetEvent( false );
   static int number;
   literal int numIterations = 100;
};

int main()
{
   
   //Create and start the reader thread.
   Thread^ myReaderThread = gcnew Thread( gcnew ThreadStart( MyMainClass::MyReadThreadProc ) );
   myReaderThread->Name = "ReaderThread";
   myReaderThread->Start();
   for ( int i = 1; i <= MyMainClass::numIterations; i++ )
   {
      Console::WriteLine( "Writer thread writing value: {0}", i );
      MyMainClass::number = i;
      
      //Signal that a value has been written.
      MyMainClass::myResetEvent->Set();
      
      //Give the Reader thread an opportunity to act.
      Thread::Sleep( 1 );

   }
   
   //Terminate the reader thread.
   myReaderThread->Abort();
}

using System;
using System.Threading;

namespace AutoResetEvent_Examples
{
	class MyMainClass
	{
		//Initially not signaled.
      const int numIterations = 100;
      static AutoResetEvent myResetEvent = new AutoResetEvent(false);
      static int number;
      
      static void Main()
		{
         //Create and start the reader thread.
         Thread myReaderThread = new Thread(new ThreadStart(MyReadThreadProc));
         myReaderThread.Name = "ReaderThread";
         myReaderThread.Start();

         for(int i = 1; i <= numIterations; i++)
         {
            Console.WriteLine("Writer thread writing value: {0}", i);
            number = i;
            
            //Signal that a value has been written.
            myResetEvent.Set();
            
            //Give the Reader thread an opportunity to act.
            Thread.Sleep(1);
         }

         //Terminate the reader thread.
         myReaderThread.Abort();
      }

      static void MyReadThreadProc()
      {
         while(true)
         {
            //The value will not be read until the writer has written
            // at least once since the last read.
            myResetEvent.WaitOne();
            Console.WriteLine("{0} reading value: {1}", Thread.CurrentThread.Name, number);
         }
      }
	}
}
Imports System
Imports System.Threading

Namespace AutoResetEvent_Examples
    Class MyMainClass
        'Initially not signaled.
        Private Const numIterations As Integer = 100
        Private Shared myResetEvent As New AutoResetEvent(False)
        Private Shared number As Integer

        <MTAThread> _
        Shared Sub Main()
            'Create and start the reader thread.
            Dim myReaderThread As New Thread(AddressOf MyReadThreadProc)
            myReaderThread.Name = "ReaderThread"
            myReaderThread.Start()

            Dim i As Integer
            For i = 1 To numIterations
                Console.WriteLine("Writer thread writing value: {0}", i)
                number = i

                'Signal that a value has been written.
                myResetEvent.Set()

                'Give the Reader thread an opportunity to act.
                Thread.Sleep(1)
            Next i

            'Terminate the reader thread.
            myReaderThread.Abort()
        End Sub 'Main

        Shared Sub MyReadThreadProc()
            While True
                'The value will not be read until the writer has written
                ' at least once since the last read.
                myResetEvent.WaitOne()
                Console.WriteLine("{0} reading value: {1}", Thread.CurrentThread.Name, number)
            End While
        End Sub 'MyReadThreadProc
    End Class 'MyMainClass
End Namespace 'AutoResetEvent_Examples

Se aplica a

Consulte también: