c# - Why is this code not threadsafe? -
i have piece of code this:
public class usercache { private dictionary<int, user> _users = new dictionary<int, user>(); public user getuser(int id) { user u = null; lock (_users) { if (_users.containskey(id)) return _users[id]; } //the below line threadsafe, no worries on that. u = retrieveuser(id); // method retrieve database; lock (_users) { _users.add(id, u); } return u; } }
i'm locking access dictionary, in team told still not threadsafe(without explanation). question - think thread safe @ all?
edit: forgot ask,what solution like.please note i'mnot looking lock whole method, retrieve user time consuming operation.
no, it's not thread-safe. imagine it's called twice @ same time same id, isn't present.
both threads far retrieveuser
, , they'd both call _users.add(id, u)
. second call fail because key exist in dictionary.
(as aside, i'd recommend using braces locks, if statements etc, sake of readability.)
Comments
Post a Comment