C# .NET 中的 ManualResetEvent 和 AutoResetEvent 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/153877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between ManualResetEvent and AutoResetEvent in .NET?
提问by Ben McNiel
I have read the documentation on this and I think I understand. An AutoResetEvent
resets when the code passes through event.WaitOne()
, but a ManualResetEvent
does not.
我已经阅读了关于此的文档,我想我明白了。AutoResetEvent
当代码通过时,An 会重置event.WaitOne()
,但 aManualResetEvent
不会。
Is this correct?
这样对吗?
采纳答案by Dan Goldstein
Yes. It's like the difference between a tollbooth and a door. The ManualResetEvent
is the door, which needs to be closed (reset) manually. The AutoResetEvent
is a tollbooth, allowing one car to go by and automatically closing before the next one can get through.
是的。这就像收费站和门之间的区别。这ManualResetEvent
是门,需要手动关闭(重置)。这AutoResetEvent
是一个收费站,允许一辆车通过并在下一辆车通过之前自动关闭。
回答by Martin Brown
The short answer is yes. The most important difference is that an AutoResetEvent will only allow one single waiting thread to continue. A ManualResetEvent on the other hand will keep allowing threads, several at the same time even, to continue until you tell it to stop (Reset it).
简短的回答是肯定的。最重要的区别是 AutoResetEvent 只允许一个等待线程继续。另一方面,ManualResetEvent 将继续允许线程(甚至多个线程)继续运行,直到您告诉它停止(重置它)。
回答by Boaz
Yes. This is absolutely correct.
是的。这是完全正确的。
You could see ManualResetEvent as a way to indicate state. Something is on (Set) or off (Reset). An occurrence with some duration. Any thread waiting for that state to happen can proceed.
您可以将 ManualResetEvent 视为指示状态的一种方式。某些东西打开(设置)或关闭(重置)。具有一定持续时间的事件。任何等待该状态发生的线程都可以继续。
An AutoResetEvent is more comparable to a signal. A one shot indication that something has happened. An occurrence without any duration. Typically but not necessarily the "something" that has happened is small and needs to be handled by a single thread - hence the automatic reset after a single thread have consumed the event.
AutoResetEvent 更类似于信号。一枪指示发生了什么事。没有任何持续时间的事件。通常但不一定发生的“事情”很小并且需要由单个线程处理 - 因此在单个线程消耗事件后自动重置。
回答by Michael Damatov
Just imagine that the AutoResetEvent
executes WaitOne()
and Reset()
as a single atomic operation.
试想一下,AutoResetEvent
executesWaitOne()
和Reset()
作为单个原子操作。
回答by Michael Damatov
Taken from C# 3.0 Nutshell book, by Joseph Albahari
摘自 Joseph Albahari 的 C# 3.0 Nutshell book
A ManualResetEvent is a variation on AutoResetEvent. It differs in that it doesn't automatically reset after a thread is let through on a WaitOne call, and so functions like a gate: calling Set opens the gate, allowing any number of threads that WaitOne at the gate through; calling Reset closes the gate, causing, potentially, a queue of waiters to accumulate until its next opened.
ManualResetEvent 是 AutoResetEvent 的变体。它的不同之处在于它不会在线程通过 WaitOne 调用后自动重置,因此其功能类似于门:调用 Set 打开门,允许门上的 WaitOne 任意数量的线程通过;调用 Reset 会关闭闸门,这可能会导致等待者队列累积,直到下一次打开。
One could simulate this functionality with a boolean "gateOpen" field (declared with the volatile keyword) in combination with "spin-sleeping" – repeatedly checking the flag, and then sleeping for a short period of time.
可以使用布尔值“gateOpen”字段(用 volatile 关键字声明)结合“spin-sleeping”来模拟此功能——反复检查标志,然后睡眠一小段时间。
ManualResetEvents are sometimes used to signal that a particular operation is complete, or that a thread's completed initialization and is ready to perform work.
ManualResetEvents 有时用于表示特定操作已完成,或线程已完成初始化并准备执行工作。
回答by Swapnil Patil
Yes, thats right.
恩,那就对了。
You can get an idea by the usage of these two.
你可以通过使用这两个来了解一下。
If you need to tell that you are finished with some work and other (threads) waiting for this can now proceed, you should use ManualResetEvent.
如果你需要告诉你已经完成了一些工作,而其他(线程)正在等待它现在可以继续,你应该使用 ManualResetEvent。
If you need to have mutual exclusive access to any resource, you should use AutoResetEvent.
如果您需要对任何资源进行互斥访问,则应使用 AutoResetEvent。
回答by Teoman shipahi
I created simple examples to clarify understanding of ManualResetEvent
vs AutoResetEvent
.
我创建了简单的例子来阐明对ManualResetEvent
vs 的理解AutoResetEvent
。
AutoResetEvent
: lets assume you have 3 workers thread. If any of those threads will call WaitOne()
all other 2 threads will stop execution and wait for signal. I am assuming they are using WaitOne()
. It is like; if I do not work, nobody works. In first example you can see that
AutoResetEvent
:假设您有 3 个工作线程。如果这些线程中的任何一个将调用WaitOne()
所有其他 2 个线程将停止执行并等待信号。我假设他们正在使用WaitOne()
. 它像是; 如果我不工作,就没有人工作。在第一个示例中,您可以看到
autoReset.Set();
Thread.Sleep(1000);
autoReset.Set();
When you call Set()
all threads will work and wait for signal. After 1 second I am sending second signal and they execute and wait (WaitOne()
). Think about these guys are soccer team players and if one player says I will wait until manager calls me, and others will wait until manager tells them to continue (Set()
)
当您调用Set()
所有线程时,所有线程都将工作并等待信号。1 秒后,我发送第二个信号,它们执行并等待 ( WaitOne()
)。想想这些人是足球队的球员,如果一个球员说我会等到经理打电话给我,而其他人会等到经理告诉他们继续(Set()
)
public class AutoResetEventSample
{
private AutoResetEvent autoReset = new AutoResetEvent(false);
public void RunAll()
{
new Thread(Worker1).Start();
new Thread(Worker2).Start();
new Thread(Worker3).Start();
autoReset.Set();
Thread.Sleep(1000);
autoReset.Set();
Console.WriteLine("Main thread reached to end.");
}
public void Worker1()
{
Console.WriteLine("Entered in worker 1");
for (int i = 0; i < 5; i++) {
Console.WriteLine("Worker1 is running {0}", i);
Thread.Sleep(2000);
autoReset.WaitOne();
}
}
public void Worker2()
{
Console.WriteLine("Entered in worker 2");
for (int i = 0; i < 5; i++) {
Console.WriteLine("Worker2 is running {0}", i);
Thread.Sleep(2000);
autoReset.WaitOne();
}
}
public void Worker3()
{
Console.WriteLine("Entered in worker 3");
for (int i = 0; i < 5; i++) {
Console.WriteLine("Worker3 is running {0}", i);
Thread.Sleep(2000);
autoReset.WaitOne();
}
}
}
In this example you can clearly see that when you first hit Set()
it will let all threads go, then after 1 second it signals all threads to wait! As soon as you set them again regardless they are calling WaitOne()
inside, they will keep running because you have to manually call Reset()
to stop them all.
在这个例子中,您可以清楚地看到,当您第一次点击Set()
它时,它将让所有线程离开,然后在 1 秒后它发出所有线程等待的信号!只要您再次设置它们,无论它们是否WaitOne()
在内部调用,它们都会继续运行,因为您必须手动调用Reset()
以将它们全部停止。
manualReset.Set();
Thread.Sleep(1000);
manualReset.Reset();
Console.WriteLine("Press to release all threads.");
Console.ReadLine();
manualReset.Set();
It is more about Referee/Players relationship there regardless of any of the player is injured and wait for playing others will continue to work. If Referee says wait (Reset()
) then all players will wait until next signal.
更多的是关于裁判/球员的关系,无论任何球员受伤并等待比赛,其他人都会继续工作。如果裁判说等待 ( Reset()
) 则所有球员将等到下一个信号。
public class ManualResetEventSample
{
private ManualResetEvent manualReset = new ManualResetEvent(false);
public void RunAll()
{
new Thread(Worker1).Start();
new Thread(Worker2).Start();
new Thread(Worker3).Start();
manualReset.Set();
Thread.Sleep(1000);
manualReset.Reset();
Console.WriteLine("Press to release all threads.");
Console.ReadLine();
manualReset.Set();
Console.WriteLine("Main thread reached to end.");
}
public void Worker1()
{
Console.WriteLine("Entered in worker 1");
for (int i = 0; i < 5; i++) {
Console.WriteLine("Worker1 is running {0}", i);
Thread.Sleep(2000);
manualReset.WaitOne();
}
}
public void Worker2()
{
Console.WriteLine("Entered in worker 2");
for (int i = 0; i < 5; i++) {
Console.WriteLine("Worker2 is running {0}", i);
Thread.Sleep(2000);
manualReset.WaitOne();
}
}
public void Worker3()
{
Console.WriteLine("Entered in worker 3");
for (int i = 0; i < 5; i++) {
Console.WriteLine("Worker3 is running {0}", i);
Thread.Sleep(2000);
manualReset.WaitOne();
}
}
}
回答by vezenkov
autoResetEvent.WaitOne()
autoResetEvent.WaitOne()
is similar to
类似于
try
{
manualResetEvent.WaitOne();
}
finally
{
manualResetEvent.Reset();
}
as an atomic operation
作为原子操作
回答by Masoud Siahkali
AutoResetEventmaintains a boolean variable in memory. If the boolean variable is false then it blocks the thread and if the boolean variable is true it unblocks the thread.
AutoResetEvent在内存中维护一个布尔变量。如果布尔变量为假,则它阻塞线程,如果布尔变量为真,则解除对线程的阻塞。
When we instantiate an AutoResetEvent object, we pass the default value of boolean value in the constructor. Below is the syntax of instantiate an AutoResetEvent object.
当我们实例化一个 AutoResetEvent 对象时,我们在构造函数中传递布尔值的默认值。下面是实例化 AutoResetEvent 对象的语法。
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
WaitOne method
等待一个方法
This method blocks the current thread and wait for the signal by other thread. WaitOne method puts the current thread into a Sleep thread state. WaitOne method returns true if it receives the signal else returns false.
该方法阻塞当前线程并等待其他线程的信号。WaitOne 方法将当前线程置于休眠线程状态。WaitOne 方法如果接收到信号则返回真,否则返回假。
autoResetEvent.WaitOne();
Second overload of WaitOne method wait for the specified number of seconds. If it does not get any signal thread continues its work.
WaitOne 方法的第二个重载等待指定的秒数。如果它没有得到任何信号线程继续它的工作。
static void ThreadMethod()
{
while(!autoResetEvent.WaitOne(TimeSpan.FromSeconds(2)))
{
Console.WriteLine("Continue");
Thread.Sleep(TimeSpan.FromSeconds(1));
}
Console.WriteLine("Thread got signal");
}
We called WaitOne method by passing the 2 seconds as arguments. In the while loop, it wait for the signal for 2 seconds then it continues its work. When the thread got the signal WaitOne returns true and exits the loop and print the "Thread got signal".
我们通过传递 2 秒作为参数来调用 WaitOne 方法。在 while 循环中,它等待信号 2 秒,然后继续工作。当线程获得信号时,WaitOne 返回 true 并退出循环并打印“线程获得信号”。
Set method
设置方法
AutoResetEvent Set method sent the signal to the waiting thread to proceed its work. Below is the syntax of calling Set method.
AutoResetEvent Set 方法将信号发送到等待线程以继续其工作。下面是调用 Set 方法的语法。
autoResetEvent.Set();
ManualResetEventmaintains a boolean variable in memory. When the boolean variable is false then it blocks all threads and when the boolean variable is true it unblocks all threads.
ManualResetEvent在内存中维护一个布尔变量。当布尔变量为假时,它阻塞所有线程,当布尔变量为真时,它解除阻塞所有线程。
When we instantiate a ManualResetEvent, we initialize it with default boolean value.
当我们实例化一个 ManualResetEvent 时,我们用默认的布尔值初始化它。
ManualResetEvent manualResetEvent = new ManualResetEvent(false);
In the above code, we initialize the ManualResetEvent with false value, that means all the threads which calls the WaitOne method will block until some thread calls the Set() method.
在上面的代码中,我们将 ManualResetEvent 初始化为 false 值,这意味着所有调用 WaitOne 方法的线程都会阻塞,直到某个线程调用 Set() 方法。
If we initialize ManualResetEvent with true value, all the threads which calls the WaitOne method will not block and free to proceed further.
如果我们将 ManualResetEvent 初始化为 true 值,则所有调用 WaitOne 方法的线程都不会阻塞,可以自由地继续进行。
WaitOne Method
等待一个方法
This method blocks the current thread and wait for the signal by other thread. It returns true if its receives a signal else returns false.
该方法阻塞当前线程并等待其他线程的信号。如果接收到信号则返回真,否则返回假。
Below is the syntax of calling WaitOne method.
下面是调用 WaitOne 方法的语法。
manualResetEvent.WaitOne();
In the second overload of WaitOne method, we can specify the time interval till the current thread wait for the signal. If within time internal, it does not receives a signal it returns false and goes into the next line of method.
在 WaitOne 方法的第二个重载中,我们可以指定当前线程等待信号的时间间隔。如果在内部时间范围内,它没有收到信号,则返回 false 并进入下一行方法。
Below is the syntax of calling WaitOne method with time interval.
以下是按时间间隔调用 WaitOne 方法的语法。
bool isSignalled = manualResetEvent.WaitOne(TimeSpan.FromSeconds(5));
We have specify 5 seconds into the WaitOne method. If the manualResetEvent object does not receives a signal between 5 seconds, it set the isSignalled variable to false.
我们在 WaitOne 方法中指定了 5 秒。如果 manualResetEvent 对象在 5 秒内没有接收到信号,它会将 isSignalled 变量设置为 false。
Set Method
设置方法
This method is used for sending the signal to all waiting threads. Set() Method set the ManualResetEvent object boolean variable to true. All the waiting threads are unblocked and proceed further.
该方法用于向所有等待线程发送信号。Set() 方法将 ManualResetEvent 对象布尔变量设置为 true。所有等待的线程都被解除阻塞并继续进行。
Below is the syntax of calling Set() method.
下面是调用 Set() 方法的语法。
manualResetEvent.Set();
Reset Method
重置方法
Once we call the Set() method on the ManualResetEvent object, its boolean remains true. To reset the value we can use Reset() method. Reset method change the boolean value to false.
一旦我们在 ManualResetEvent 对象上调用 Set() 方法,它的布尔值就会保持为真。要重置值,我们可以使用 Reset() 方法。Reset 方法将布尔值更改为 false。
Below is the syntax of calling Reset method.
下面是调用 Reset 方法的语法。
manualResetEvent.Reset();
We must immediately call Reset method after calling Set method if we want to send signal to threads multiple times.
如果我们想多次向线程发送信号,我们必须在调用 Set 方法后立即调用 Reset 方法。
回答by Teoman shipahi
OK, normally it does not a good practice to add 2 answers in same thread, but I did not want to edit/delete my previous answer, since it can help on another manner.
好的,通常在同一线程中添加 2 个答案不是一个好习惯,但我不想编辑/删除我以前的答案,因为它可以以另一种方式提供帮助。
Now, I created, much more comprehensive, and easy to understand, run-to-learn console app snippet below.
现在,我在下面创建了更全面且易于理解的运行学习控制台应用程序片段。
Just run the examples on two different consoles, and observe behaviour. You will get much more clear idea there what is happening behind the scenes.
只需在两个不同的控制台上运行示例,并观察行为。你会更清楚地了解幕后发生的事情。
Manual Reset Event
手动重置事件
using System;
using System.Threading;
namespace ConsoleApplicationDotNetBasics.ThreadingExamples
{
public class ManualResetEventSample
{
private readonly ManualResetEvent _manualReset = new ManualResetEvent(false);
public void RunAll()
{
new Thread(Worker1).Start();
new Thread(Worker2).Start();
new Thread(Worker3).Start();
Console.WriteLine("All Threads Scheduled to RUN!. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("Main Thread is waiting for 15 seconds, observe 3 thread behaviour. All threads run once and stopped. Why? Because they call WaitOne() internally. They will wait until signals arrive, down below.");
Thread.Sleep(15000);
Console.WriteLine("1- Main will call ManualResetEvent.Set() in 5 seconds, watch out!");
Thread.Sleep(5000);
_manualReset.Set();
Thread.Sleep(2000);
Console.WriteLine("2- Main will call ManualResetEvent.Set() in 5 seconds, watch out!");
Thread.Sleep(5000);
_manualReset.Set();
Thread.Sleep(2000);
Console.WriteLine("3- Main will call ManualResetEvent.Set() in 5 seconds, watch out!");
Thread.Sleep(5000);
_manualReset.Set();
Thread.Sleep(2000);
Console.WriteLine("4- Main will call ManualResetEvent.Reset() in 5 seconds, watch out!");
Thread.Sleep(5000);
_manualReset.Reset();
Thread.Sleep(2000);
Console.WriteLine("It ran one more time. Why? Even Reset Sets the state of the event to nonsignaled (false), causing threads to block, this will initial the state, and threads will run again until they WaitOne().");
Thread.Sleep(10000);
Console.WriteLine();
Console.WriteLine("This will go so on. Everytime you call Set(), ManualResetEvent will let ALL threads to run. So if you want synchronization between them, consider using AutoReset event, or simply user TPL (Task Parallel Library).");
Thread.Sleep(5000);
Console.WriteLine("Main thread reached to end! ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
}
public void Worker1()
{
for (int i = 1; i <= 10; i++)
{
Console.WriteLine("Worker1 is running {0}/10. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(5000);
// this gets blocked until _autoReset gets signal
_manualReset.WaitOne();
}
Console.WriteLine("Worker1 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
}
public void Worker2()
{
for (int i = 1; i <= 10; i++)
{
Console.WriteLine("Worker2 is running {0}/10. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(5000);
// this gets blocked until _autoReset gets signal
_manualReset.WaitOne();
}
Console.WriteLine("Worker2 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
}
public void Worker3()
{
for (int i = 1; i <= 10; i++)
{
Console.WriteLine("Worker3 is running {0}/10. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(5000);
// this gets blocked until _autoReset gets signal
_manualReset.WaitOne();
}
Console.WriteLine("Worker3 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
}
}
}
Auto Reset Event
自动重置事件
using System;
using System.Threading;
namespace ConsoleApplicationDotNetBasics.ThreadingExamples
{
public class AutoResetEventSample
{
private readonly AutoResetEvent _autoReset = new AutoResetEvent(false);
public void RunAll()
{
new Thread(Worker1).Start();
new Thread(Worker2).Start();
new Thread(Worker3).Start();
Console.WriteLine("All Threads Scheduled to RUN!. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("Main Thread is waiting for 15 seconds, observe 3 thread behaviour. All threads run once and stopped. Why? Because they call WaitOne() internally. They will wait until signals arrive, down below.");
Thread.Sleep(15000);
Console.WriteLine("1- Main will call AutoResetEvent.Set() in 5 seconds, watch out!");
Thread.Sleep(5000);
_autoReset.Set();
Thread.Sleep(2000);
Console.WriteLine("2- Main will call AutoResetEvent.Set() in 5 seconds, watch out!");
Thread.Sleep(5000);
_autoReset.Set();
Thread.Sleep(2000);
Console.WriteLine("3- Main will call AutoResetEvent.Set() in 5 seconds, watch out!");
Thread.Sleep(5000);
_autoReset.Set();
Thread.Sleep(2000);
Console.WriteLine("4- Main will call AutoResetEvent.Reset() in 5 seconds, watch out!");
Thread.Sleep(5000);
_autoReset.Reset();
Thread.Sleep(2000);
Console.WriteLine("Nothing happened. Why? Becasuse Reset Sets the state of the event to nonsignaled, causing threads to block. Since they are already blocked, it will not affect anything.");
Thread.Sleep(10000);
Console.WriteLine("This will go so on. Everytime you call Set(), AutoResetEvent will let another thread to run. It will make it automatically, so you do not need to worry about thread running order, unless you want it manually!");
Thread.Sleep(5000);
Console.WriteLine("Main thread reached to end! ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
}
public void Worker1()
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Worker1 is running {0}/5. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(500);
// this gets blocked until _autoReset gets signal
_autoReset.WaitOne();
}
Console.WriteLine("Worker1 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
}
public void Worker2()
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Worker2 is running {0}/5. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(500);
// this gets blocked until _autoReset gets signal
_autoReset.WaitOne();
}
Console.WriteLine("Worker2 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
}
public void Worker3()
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Worker3 is running {0}/5. ThreadId: {1}.", i, Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(500);
// this gets blocked until _autoReset gets signal
_autoReset.WaitOne();
}
Console.WriteLine("Worker3 is DONE. ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
}
}
}