multithreading - Please can someone give me a simple example of how to use System.Monitor in C#? -


i find system.monitor confusing, although understand threading, locks, deadlocks, race conditions, dining philosophers , jazz. use manualresetevent() inter-thread co-ordination, know that's heavyweight kernel object, , system.monitor (enter/pulse, etc.) more efficient. i've googled , googled cannot find sensible example.

i grateful if crew explain potentially wonderful construct me :-)

here's simple example; call wait releases lock (allowing worker obtain it) , adds main thread lock-object's pending queue. worker obtains lock, , calls pulse: moves main thread lock-object's ready queue. when worker releases lock, main can resume work.

note lock(obj) {...} compiler-candy monitor.enter/monitor.exit in try/finally block.

[edit: changed sample move lock(sync) earlier, avoid (unlikely) risk of missed pulse]

    static void main()     {         object sync = new object();         lock (sync)         {             threadpool.queueuserworkitem(worker, sync);             console.writeline("main sleeping");              // wait worker tell ready             monitor.wait(sync);             console.writeline("main woke up!");         }         console.writeline("press key...");         console.readkey();     }     static void worker(object sync)     {         console.writeline("worker started; sleep");         thread.sleep(5000);         console.writeline("worker pulse");         lock (sync)         { // notify main did interesting             monitor.pulse(sync);             console.writeline("worker pulsed; release lock");         }         console.writeline("worker done");     } 

Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -