I have code listed here: Threading and Sockets.
The answer to that question was to modify isListening
with volatile
. As I remarked, that modifier allowed me to access the variable from another thread. After reading MSDN, I realized that I was reading isListening from the following newly created thread process.
So, my questions now:
Is volatile
the preferred method,since I am basically making a non-thread safe request on a variable? I have read about the Interlocked class and wondered if this was something that would be better to use in my code. Interlocked looks similar to what lock(myObj)
is doing - but with a little more 'flair' and control. I do know that simply applying a lock(myObj)
code block around isListening
did not work.
Should I implement the Interlocked class?
Thank you for your time and responses.
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 providing its type is bool, char, byte, sbyte, short, ushort, int, uint, float, and reference types. See here for details.
In the example from your other post, the reason you have to mark the field as volatile
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 here for details on the volatile
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 volatile
keyword can only be used for your field because it is of type bool. Had it been a double, for example, the volatile
keyword wouldn't work, and you'd have to use a lock.
The Interlocked
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 Interlocked
class simply provides some convenience functions so you don't have to lock the variable yourself while the increment operation is performed.
What you are doing with the isListening
flag does not require use of the Interlocked
class. Marking the field as volatile is sufficient.