c# - Is not checking key existence in a static dictionary thread-safe? Resharper thinks it's not -
resharper suggests wrapping return dic.contains("v1");
in lock statement saying "the field used inside synchronized block , used without synchronization":
public class myclass { private static dictionary<string, string> _dic = new dictionary<string, string>(); protected bool v1exist() { return dic.contains("v1"); } }
however not see why lock needed in example. looks safe-thread me. please advise
it's known dictionary not thread-safe, should synchronize both writes , reads. if want specific example of can go wrong - consider small application:
static void main(string[] args) { var dict = new dictionary<int, int>(); dict.add(0, 0); new thread(() => { (int = 1; < int.maxvalue; i++) { lock (dict) { dict.add(i, i); dict.remove(i); } } }).start(); new thread(() => { while (true) { if (!dict.containskey(0)) throw new exception("cannot happen?"); } }).start(); console.readkey(); }
we create dictionary 1 entry key 0
, run 2 threads. first thread adds , removes keys dictionary, note not remove item key 0. item key 0 present.
second threads checks if there item key 0 , throws exception if not. might think can never happen, because never remove item key 0, not true. if run application throw "cannot happen?" exception immediately. if add lock around containskey
- never happen.
so in short, things might go horribly wrong if not synchronizing access not thread safe structures properly, reads. , might not notice that, , have hard time debugging such issues, because application might behave fine.
Comments
Post a Comment