Partager via


AutoResetEvent Constructor

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Initializes a new instance of the AutoResetEvent class with a Boolean value that indicates whether to set the initial state to signaled.

Namespace:  System.Threading
Assembly:  mscorlib (in mscorlib.dll)

Syntax

'Declaration
Public Sub New ( _
    initialState As Boolean _
)
public AutoResetEvent(
    bool initialState
)

Parameters

  • initialState
    Type: System.Boolean
    true to set the initial state to signaled; false to set the initial state to non-signaled.

Remarks

Specifying true for initialState creates an AutoResetEvent in the signaled state. This is useful if you want the first thread that waits for the AutoResetEvent to be released immediately, without blocking.

Examples

The following example shows the use of this constructor to create an AutoResetEvent that is initially in the non-signaled state. The example uses an AutoResetEvent to synchronize the activities of two threads. The first thread executes MyWriteThreadProc. It writes values to the protected resource, which is a static (Shared in Visual Basic) field named number. The second thread executes the static MyReadThreadProc method, which reads the values written by MyWriteThreadProc.

The MyReadThreadProc method waits for the AutoResetEvent. When MyWriteThreadProc calls the Set method on the AutoResetEvent, the MyReadThreadProc method reads one value. The AutoResetEvent immediately resets, so the MyReadThreadProc method waits again.

The program logic guarantees that the MyReadThreadProc method will never read the same value two times. It does not guarantee that the MyReadThreadProc method will read every value written by MyWriteThreadProc. That guarantee would require a second AutoResetEvent lock.

After each write operation, MyWriteThreadProc yields by calling the Thread.Sleep method, to give the second thread a chance to execute. Otherwise, on a single-processor computer MyWriteThreadProc would write many values between any two read operations.

The Demo method starts the two thread procedures. The threads write their output to a StringBuilder object, which is protected from concurrent access by lock statements (SyncLock statements in Visual Basic). The MyWriteThreadProc method appends the final output to the TextBlock control by using the Dispatcher property to obtain a Dispatcher object for the TextBlock, and then using the Dispatcher.BeginInvoke method to make the cross-thread call to the UI thread.

Imports System.Threading
Imports System.Text

Class Example
    Private Const numIterations As Integer = 10

    ' Create an AutoResetEvent that is initially not signaled.
    Private Shared myResetEvent As New AutoResetEvent(False)

    Private Shared number As Integer
    Private Shared running As Boolean = True
    Private Shared output As New StringBuilder()
    Private Shared outputBlock As System.Windows.Controls.TextBlock

    Public Shared Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)

        Example.outputBlock = outputBlock

        'Create and start the reader thread.
        Dim myReaderThread As New Thread(AddressOf MyReadThreadProc)
        myReaderThread.Name = "ReaderThread"
        myReaderThread.Start()

        'Create and start the writer thread.
        Dim myWriterThread As New Thread(AddressOf MyWriteThreadProc)
        myWriterThread.Name = "WriterThread"
        myWriterThread.Start()

    End Sub

    Shared Sub MyReadThreadProc()

        While running
            'The value will not be read until the writer has written
            ' at least once since the last read.
            myResetEvent.WaitOne()

            SyncLock output
                output.AppendLine(String.Format("{0} reading value: {1}", _
                    Thread.CurrentThread.Name, number))
            End SyncLock
        End While
    End Sub 

    Shared Sub MyWriteThreadProc()

        For i As Integer = 1 To numIterations
            SyncLock output
                output.AppendLine(String.Format("{0} writing value: {1}", _
                    Thread.CurrentThread.Name, i))
            End SyncLock

            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.
        running = False
        myResetEvent.Set()

        SyncLock output
            ' Append the output from the example to the TextBlock control,
            ' on the UI thread.
            outputBlock.Dispatcher.BeginInvoke(displayHelper, output.ToString())
        End SyncLock
    End Sub 

    ' In order to update the TextBlock object, which is on the UI thread, you must
    ' make a cross-thread call by using the Dispatcher object that is associated 
    ' with the TextBlock. The DisplayOutput helper method and its delegate, 
    ' displayHelper, are used by the BeginInvoke method of the Dispatcher object
    ' to append text to the TextBlock. 
    '
    Private Shared displayHelper As New Action(Of String)(AddressOf DisplayOutput)
    Private Shared Sub DisplayOutput(ByVal msg As String)
        outputBlock.Text &= msg 
    End Sub

End Class 

' This code example produces output similar to the following:
'
'WriterThread writing value: 1
'ReaderThread reading value: 1
'WriterThread writing value: 2
'ReaderThread reading value: 2
'WriterThread writing value: 3
'ReaderThread reading value: 3
'WriterThread writing value: 4
'ReaderThread reading value: 4
'WriterThread writing value: 5
'ReaderThread reading value: 5
'WriterThread writing value: 6
'ReaderThread reading value: 6
'WriterThread writing value: 7
'ReaderThread reading value: 7
'WriterThread writing value: 8
'ReaderThread reading value: 8
'WriterThread writing value: 9
'ReaderThread reading value: 9
'WriterThread writing value: 10
'ReaderThread reading value: 10
using System;
using System.Threading;
using System.Text;

class Example
{
    private const int numIterations = 10;

    // Create an AutoResetEvent that is initially not signaled.
    private static AutoResetEvent myResetEvent = new AutoResetEvent(false);

    private static int number;
    private static bool running = true;
    private static StringBuilder output = new StringBuilder();
    private static System.Windows.Controls.TextBlock outputBlock;

    public static void Demo(System.Windows.Controls.TextBlock outputBlock)
    {
        Example.outputBlock = outputBlock;

        // Create and start the reader thread.
        Thread myReaderThread = new Thread(MyReadThreadProc);
        myReaderThread.Name = "ReaderThread";
        myReaderThread.Start();

        // Create and start the writer thread.
        Thread myWriterThread = new Thread(MyWriteThreadProc);
        myWriterThread.Name = "WriterThread";
        myWriterThread.Start();
    }

    public static void MyReadThreadProc()
    {
        while (running)
        {
            // The value will not be read until the writer has written
            // at least once since the last read.
            myResetEvent.WaitOne();

            lock (output)
            {
                output.AppendLine(String.Format("{0} reading value: {1}", 
                    Thread.CurrentThread.Name, number));
            }
        }
    }

    public static void MyWriteThreadProc()
    {
        for(int i = 1; i <= numIterations; i++)
        {
            lock (output)
            {
                output.AppendLine(String.Format("{0} writing value: {1}", 
                    Thread.CurrentThread.Name, 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.
        running = false;
        myResetEvent.Set();

        lock (output)
        {
            // Append the output from the example to the TextBlock control.
            // In order to update the TextBlock object, which is on the UI thread,
            // you must make a cross-thread call by using the Dispatcher object 
            // that is associated with the TextBlock.
            outputBlock.Dispatcher.BeginInvoke(delegate () {
                outputBlock.Text += output.ToString(); });
        }
    }
}

/* This code example produces output similar to the following:

WriterThread writing value: 1
ReaderThread reading value: 1
WriterThread writing value: 2
ReaderThread reading value: 2
WriterThread writing value: 3
ReaderThread reading value: 3
WriterThread writing value: 4
ReaderThread reading value: 4
WriterThread writing value: 5
ReaderThread reading value: 5
WriterThread writing value: 6
ReaderThread reading value: 6
WriterThread writing value: 7
ReaderThread reading value: 7
WriterThread writing value: 8
ReaderThread reading value: 8
WriterThread writing value: 9
ReaderThread reading value: 9
WriterThread writing value: 10
ReaderThread reading value: 10
 */

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.