Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Take a look at <a href="http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent.aspx" rel="nofollow noreferrer">AutoResetEvent</a> and <a href="http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx" rel="nofollow noreferrer">ManualResetEvent</a>. They are signals that makes synchronisation between threads possible.</p> <p>The first thread that needs to wait for something to get done will do myEvent.<a href="http://msdn.microsoft.com/en-us/library/58195swd.aspx" rel="nofollow noreferrer">WaitOne</a>(), which blocks until the other thread calls myEvent.<a href="http://msdn.microsoft.com/en-us/library/system.threading.eventwaithandle.set.aspx" rel="nofollow noreferrer">Set</a>().</p> <p>Let's say we have two threads, where one of them needs to do some kind of initialisation before the other thread can continue. You then share a AutoResetEvent between the two, let's call it myEvent.</p> <pre><code>// Signal example using System; using System.Threading; class MySync { private readonly AutoResetEvent _myEvent; public MySync(AutoResetEvent myEvent) { _myEvent = myEvent; } public void ThreadMain(object state) { Console.WriteLine("Starting thread MySync"); _myEvent.WaitOne(); Console.WriteLine("Finishing thread MySync"); } } class Program { static void Main(string[] args) { AutoResetEvent myEvent = new AutoResetEvent(false); MySync mySync = new MySync(myEvent); ThreadPool.QueueUserWorkItem(mySync.ThreadMain); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); myEvent.Set(); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); Console.WriteLine("Finishing"); } } </code></pre> <p>Don't confuse this with a shared resource where the access order doesn't matter. For example, if you have a shared list or a shared dictionary you need to wrap it in a mutex in order to guarantee that they execute correctly.</p> <pre><code>// Mutex example object mySync = new object(); Dictionary&lt;int, int&gt; myDict = new Dictionary&lt;int, int&gt;(); void threadMainA() { lock(mySync) { mySync[foo] = bar; } } void threadMainB() { lock(mySync) { mySync[bar] = foo; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload