Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is atomical, so threadsafe</p> <pre><code>int sync = Interlocked.CompareExchange(ref syncPoint, 1, 0); if (sync == 0) </code></pre> <p>It means: if the syncPoint is 0, put it at 1, give me the old value (so 0) and put it in sync (a local variable). Then check if the exchange was done (so if the old value was 0)</p> <p>What I would make different is instead of </p> <pre><code>syncPoint = 0; </code></pre> <p>I would use</p> <pre><code>Interlocked.Exchange(ref syncPoint, 0); </code></pre> <p>just to be sure that other threads can immediately see that the "lock" is free, otherwise the current thread could delay "writing" that <code>syncPoint = 0</code> and no other threads could enter the "lock".</p> <p>BUT</p> <p>in the example given this is not a problem: <code>HandleElapsed</code> is called in response to a event (the Timer probably uses OS timers)... I can't even imagine that after the event has been handled there isn't any code that generates a memory barrier (inside the .NET code or inside the Windows OS code), so that the <code>syncPoint</code> update <strong>will</strong> be made visible to other threads. The only difference is that perhaps it will be made visible "some hundred lines below that point" instead of "immediately now".</p> <p>Let's check this theory: from <a href="http://msdn.microsoft.com/en-us/library/System.Timers.Timer.aspx" rel="nofollow">here</a></p> <blockquote> <p>If the SynchronizingObject property is null, the Elapsed event is raised on a ThreadPool thread. If processing of the Elapsed event lasts longer than Interval, the event might be raised again on another ThreadPool thread. In this situation, the event handler should be reentrant.</p> </blockquote> <p>So, the event is fired on a new <code>ThreadPool</code> thread... That after the event is surely returned to the <code>ThreadPool</code>... Ok... There is surely a <code>MemoryBarrier</code> somewhere (at least to return the thread to the <code>ThreadPool</code> or to <code>Sleep</code> if the same thread is used more than once)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

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