c# - Is this class threadsafe? -


Is this ValueStore class threadsoff? Should the lock scope in the gate key be increased around yield yield?

  Public class ValueStore {Private Redonly Object _ Locker = New Object (); Private Readonly Dictionary & lt; String, int & gt; _data = New Dictionary & lt; String, int & gt; (); Public Prices Store (dictionary & lt; string, int & gt; data) {_data = data; } Public IEnumerable & lt; Int & gt; GetInt (string key) {IEnumerable & lt; KeyValuePair & lt; String, int & gt; & Gt; Selected; Lock (_ locker) {selected = _data.Where (x => x.Key.Equals (key)); } Foreach (keyvaluePair  gt; selected in pairs) {yield returns pair. value; Unit tests can be corrected:  
  [TestFixture] Public class ValueStoreTest {[Test] Public Zero test1 () {Dictionary & lt; String, int & gt; Data = new dictionary & lt; String, int & gt; (); {Data.Add (i.ToString (), i) for (int i = 0; i & lt; 100000; i ++); } ValueStore vs. = New Value Story (Data); For (Int i = 0; I <900000; i ++) {Threadpool.QUUsverWarkTime (for representative {for (Junk = 0; J & lt; 100000; J ++) {Inmemberable & lieutenant; et end GT; D = Vs. GateInt (J.Toostring));}}); }}}}  

No, this is definitely not thread-safe.

The fact is that it uses the dictionary passed by the client, it means that when the client changes it, then you have no control when you where Sections are applied, even then you are locking it only - but it does not really do any repetition. You need to hold a lock while running on the results - but as I said earlier, it can not stop the customer from changing the dictionary at any time.

If you highlighted the class and data only in it (i.e. it was preserved from outside world) you can make it completely thread-safe if you request that the client code Do not mutate, you do not need lock at all, because without any authors the dictionaries are safe to read.


Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -