AutoResetEvent(Boolean) 构造函数
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
使用布尔值初始化类的新实例 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 的 Visual Basic 字段中的 Shared (number)。 第二个线程执行静态 ThreadProc 方法,该方法读取由 Main它写入的值。
该方法 ThreadProc 等待 AutoResetEvent. 调用该方法MainSet时AutoResetEvent,该方法ThreadProc将读取一个值。 立即 AutoResetEvent 重置,因此该方法 ThreadProc 会再次等待。
程序逻辑保证 ThreadProc 该方法永远不会读取相同的值两次。 它不保证 ThreadProc 该方法将读取由 Main该方法写入的每个值。 这种保证需要第二 AutoResetEvent 个锁。
每次写入操作后, Main 通过调用 Thread.Sleep 方法生成第二个线程,使第二个线程有机会执行。 否则,在单处理器计算机上 Main ,会在任意两个读取操作之间写入许多值。
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