I was wondering: Locking allows only 1 thread to enter a code region
And wait handles is for signaling : :
Signaling is when one thread waits until it receives notification from another.
So I thought to myself , can this be used to replace a lock ?
something like :
Thread number 1 --please enter ( autoreset --> autlock)
dowork...
finish work...
set signal to invite the next thread
So I wrote this :
/*1*/ static EventWaitHandle _waitHandle = new AutoResetEvent(true);
/*2*/
/*3*/ volatile int i = 0;
/*4*/ void Main()
/*5*/ {
/*6*/
/*7*/ for (int k = 0; k < 10; k++)
/*8*/ {
/*9*/ var g = i;
/*10*/ Interlocked.Increment(ref i);
/*11*/ new Thread(() = > DoWork(g)).Start();
/*12*/
/*13*/ }
/*14*/
/*15*/ Console.ReadLine();
/*16*/ }
/*17*/
/*18*/
/*19*/ void DoWork(object o)
/*20*/ {
/*21*/ _waitHandle.WaitOne();
/*22*/ Thread.Sleep(10);
/*23*/ Console.WriteLine((int) o + "Working...");
/*24*/ _waitHandle.Set();
/*25*/
/*26*/ }
as you can see : lines #21 , #24 are the replacement for the lock.
Question :
- Is it a valid replacement ? ( not that i will replace
lock
, but want to know about usages scenarios) - When should I use each ?
Thank you.
strange but SO does not contain a question regarding _lock vs EventWaitHandle_
AutoResetEvent /waithdnales
are not shared between processes. the writer confused with Mutex. anyway he is wrong. ( about that). – Sackbut