So, I've got a Dictionary<KType,VType> Foo
In one thread I have:
void Thread1() {
...
if (!Foo.TryGetValue(key, out v)) {
Foo.Add(new VType());
}
...
}
The only time Foo
is ever accessed by another thread is by a TryGetValue
.
So, how much to I need to lock? Can I do something like:
void Thread1() {
...
if (!Foo.TryGetValue(key, out v)) {
lock (syncobj) {
Foo.Add(new VType());
}
}
...
}
void Thread2() {
...
lock (syncobj) {
Foo.TryGetValue(key, out v))
}
...
}
The Thread1 is 90% of the program computation and TryGetValue
is called many times. So, preferably, I would like to not have to call lock every time.