Tuesday, 15 September 2015

c# - When to lock a thread-safe collection in .net ? ( & when not to lock ? ) -


OK, I've read.

The former questions in the center of Java show the answer to the question and subsequent question that I do not need to lock the archive because they are thread-safe (which I have thought)


Now my question is coming, I see that lots of developers have started using new thread-safe archives (on Gitanj and in my organization). However, often they do not remove the lock around reading & amp; I do not understand the writing operation. There is not a thread-safe archive ... OK, Thread-safe Completely ?


What can be the implication of not locking a thread - a secure archive?

Edit: PS: This is my case,

I have many classes, and some of these are a feature On them. Many times I need to check whether there is a given type of characteristic or not (of course by reflection) it can be expensive on display, so a concurrent extension & lt; String, bull & gt; to make a cache. The name of the string is being typed and the boolele specifies if it has the attribute. First of all, the cache is empty; this plan was to keep adding this and when necessary, I came to the method of ConcurrentDictionary . And my question is about that, if I should call this method without locking?

The comment on MSDN says:

If you call GetOrAdd simultaneously on different threads, addValueFactory can be called multiple times, but every call For the dictionary its key / value pair can not be added .

You should not lock secure storage from any thread, it already locked Exposes ways to update the archive, use their purpose as intended.

Thread secure storage can not match your needs for example if you want to stop modification, while a calculator is opened on the archive (provided threads allow secure archive modifications If this is the case then you will make better use of regular collection and lock it everywhere. Internal locks for safe storage from thread are not available publicly.

It is difficult to answer in relation to not locking a thread-safe archive. You do not need to lock a thread-protected archive but you may have to lock your code Difficult to tell without seeing the code.


Yes method thread is safe, but if you add an add to the same key at the same time, then it can call AddValueFactory several times. At the end only one value will be added, the other will be abandoned. It can not be a problem ... you have to see how many times you can reach this situation, but I think it is not common and you can live with the performance penalty in the shore case which can never be so may.

You can also create your own dictionary in a static CTOR or before you need it. In this way, the timetable gets filled once and you never write it. Dictionary reads only and you do not have any lock safe collection.


No comments:

Post a Comment