Suppose you have this code:
class Program
{
static void Main(string[] args)
{
var are = new AutoResetEvent(false);
for (int i = 0; i < 10; i++)
{
var j = i;
new Thread(() =>
{
Console.WriteLine("Started {0}", j);
are.WaitOne();
Console.WriteLine("Continued {0}", j);
}).Start();
}
are.Set();
Console.ReadLine();
}
}
You would then get output such as this:
Started 0
Started 1
Started 2
Started 3
Started 4
Started 5
Started 6
Started 7
Started 8
Continued 0
Started 9
But if you instead use ManualResetEvent
:
class Program
{
static void Main(string[] args)
{
var mre = new ManualResetEvent(false);
for (int i = 0; i < 10; i++)
{
var j = i;
new Thread(() =>
{
Console.WriteLine("Started {0}", j);
mre.WaitOne();
Console.WriteLine("Continued {0}", j);
}).Start();
}
mre.Set();
Console.ReadLine();
}
}
Then you'll get what I guess is the expected behavior:
Started 0
Started 1
Started 2
Started 3
Started 4
Started 5
Started 6
Started 7
Started 8
Started 9
Continued 1
Continued 8
Continued 7
Continued 4
Continued 5
Continued 6
Continued 3
Continued 0
Continued 9
Continued 2
Of course, as the name implies, ManualResetEvent
needs to be manually reset, whereas AutoResetEvent
automatically resets after the first WaitOne
has released its thread.