AutoResetEvent(Boolean) Construtor

Definição

Inicializa uma nova instância da AutoResetEvent classe com um valor booleano que indica se deve definir o estado inicial para sinalizado.

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

true definir o estado inicial para sinalizado; false para definir o estado inicial para não-sinalizado.

Exemplos

O exemplo seguinte utiliza um AutoResetEvent para sincronizar as atividades de dois threads. O primeiro thread, que é o thread de aplicação, executa Main. Escreve valores para o recurso protegido, que é um campo static (Shared em Visual Basic) denominado number. O segundo thread executa o método estático ThreadProc , que lê os valores escritos por Main.

O ThreadProc método espera pelo AutoResetEvent. Quando Main chama o Set método no AutoResetEvent, o ThreadProc método lê um valor. Reinicia-se AutoResetEvent imediatamente, por isso o ThreadProc método espera novamente.

A lógica do programa garante que o ThreadProc método nunca lê o mesmo valor duas vezes. Não garante que o ThreadProc método leia todos os valores escritos por Main. Essa garantia exigiria uma segunda AutoResetEvent fechadura.

Após cada operação de escrita, Main obtém, chamando o Thread.Sleep método, para dar à segunda thread a hipótese de executar. Caso contrário, num computador Main de processador único escreveria muitos valores entre quaisquer duas operações de leitura.

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

        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
    End Class
End Namespace 'AutoResetEvent_Examples

Aplica-se a

Ver também