Are unresettable "flags" threadsafe in C#/.NET? -
(note: asked question, answer specific java, , asking same question c# , .net framework. not duplicate.)
i have been using pattern while, came think might not ok this. basically, use variant of pattern:
public class sampleasync { public sampleasync() { } private bool completed; public void start() { var worker = new backgroundworker(); worker.dowork += (sender, e) => { //... on different thread completed = true; }; worker.runworkerasync(); } public void update() { if (!completed) return; //... else } }
*the user responsible making sure start
called once. update
called wherever , whenever.
i've assumed threadsafe in c#/the .net framework, because though nothing strictly synchronized, ever set completed
true. once has been observed true
, not reset false
. initialized false in constructor, definition thread safe (unless stupid in it). so, thread safe use unresettable flags in way? (and if so, provide performance benefits?)
thanks
your code thread safe, because bool
atomic type.
msdn:
reads , writes of following data types atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, , reference types. in addition, reads , writes of enum types underlying type in previous list atomic. reads , writes of other types, including long, ulong, double, , decimal, user-defined types, not guaranteed atomic. aside library functions designed purpose, there no guarantee of atomic read-modify-write, such in case of increment or decrement.
see: http://msdn.microsoft.com/en-us/library/aa691278(v=vs.71).aspx
please mark field volatile
:
private volatile bool completed;
msdn:
the volatile keyword indicates field can modified in program such operating system, hardware, or concurrently executing thread.
see: http://msdn.microsoft.com/en-us/library/x13ttww7(v=vs.71).aspx
Comments
Post a Comment