Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If all you are doing is reading and writing a variable across multiple threads in C#, then you do not have to worry about synchronizing access to (locking) that variable <em>providing its type is bool, char, byte, sbyte, short, ushort, int, uint, float, and reference types.</em> See <a href="http://msdn.microsoft.com/en-us/library/aa691278(VS.71).aspx" rel="nofollow noreferrer">here</a> for details.</p> <p>In the example from your other post, the reason you have to mark the field as <code>volatile</code> is to ensure that it is not subject to compiler optimizations and that the most current value is present in the field at all times. See <a href="http://msdn.microsoft.com/en-us/library/x13ttww7.aspx" rel="nofollow noreferrer">here</a> for details on the <code>volatile</code> keyword. Doing this allows that field to be read and written across threads without having to lock (synchronize access to) it. But keep in mind, the <code>volatile</code> keyword can only be used for <em>your</em> field because it is of type bool. Had it been a double, for example, the <code>volatile</code> keyword wouldn't work, and you'd have to use a lock.</p> <p>The <code>Interlocked</code> class is used for a specialized purpose, namely incrementing, decrementing, and exchanging values of (typically) numeric types. These operations are not atomic. For example, if you are incrementing a value in one thread and trying to read the resulting value in another thread, you would normally have to lock the variable to prevent reading intermediate results. The <code>Interlocked</code> class simply provides some convenience functions so you don't have to lock the variable yourself while the increment operation is performed.</p> <p>What you are doing with the <code>isListening</code> flag does not require use of the <code>Interlocked</code> class. Marking the field as volatile is sufficient.</p>
 

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