AutoResetEvent(Boolean) Конструктор

Определение

Инициализирует новый экземпляр класса AutoResetEvent логическим значением, показывающим наличие сигнального состояния.

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

Параметры

initialState
Boolean

Значение true для задания начального состояния сигнальным; false для задания несигнального начального состояния.

Примеры

В следующем примере используется AutoResetEvent для синхронизации действий двух потоков. Первый поток, который является потоком приложения, выполняет Main. Он записывает значения в защищенный ресурс, который является полем static (Shared в Visual Basic) с именем number. Второй поток выполняет статический ThreadProc метод, который считывает значения, записанные .Main

Метод ThreadProc ожидает .AutoResetEvent При Main вызове Set метода в метод ThreadProc считывает AutoResetEventодно значение. Объект AutoResetEvent немедленно сбрасывается, поэтому ThreadProc метод снова ожидает.

Логика программы гарантирует, что ThreadProc метод никогда не считывает одно и то же значение два раза. Это не гарантирует, что ThreadProc метод будет считывать все значения, записанные .Main Для этого потребуется вторая AutoResetEvent блокировка.

После каждой Main операции записи возвращается путем вызова Thread.Sleep метода , чтобы дать возможность выполнить второй поток. В противном случае на компьютере Main с одним процессором будет записываться много значений между любыми двумя операциями чтения.

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

Применяется к

См. также раздел