Ler em inglês

Partilhar via


AutoResetEvent(Boolean) Construtor

Definição

Inicializa uma nova instância da classe AutoResetEvent com um valor booliano que indica se é necessário definir o estado inicial como sinalizado.

C#
public AutoResetEvent (bool initialState);

Parâmetros

initialState
Boolean

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

Exemplos

O exemplo a seguir usa um AutoResetEvent para sincronizar as atividades de dois threads. O primeiro thread, que é o thread do aplicativo, é Mainexecutado. Ele grava valores no recurso protegido, que é um static campo (Shared em Visual Basic) chamado number. O segundo thread executa o método estático ThreadProc , que lê os valores gravados por Main.

O ThreadProc método aguarda o AutoResetEvent. Quando Main chama o Set método no AutoResetEvent, o ThreadProc método lê um valor. A AutoResetEvent redefinição imediata, portanto, o ThreadProc método aguarda novamente.

A lógica do programa garante que o ThreadProc método nunca lerá o mesmo valor duas vezes. Ele não garante que o ThreadProc método leia todos os valores escritos por Main. Essa garantia exigiria um segundo AutoResetEvent bloqueio.

Após cada operação de gravação, Main produz chamando o Thread.Sleep método para dar ao segundo thread a chance de executar. Caso contrário, em um computador Main de processador único escreveria muitos valores entre as duas operações de leitura.

C#
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);
         }
      }
    }
}

Aplica-se a

Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Confira também