locking on dictionary of structs not working between 2 threads?
C#, .Net2.0, XP, Zen
I have 2 thr开发者_开发知识库eads accessing a shared dictionary of structures, each thread via an event. At the beginning of the event I lock the dictionary, remove some structures, and exit the lock+event. Yet somehow the 2nd thread|event is finding some of the removed structures.
Conceptually I must be doing something wrong for this to be happening? I thought locking was supposed to make it thread safe?
Two things I can suggest without seeing the code:
- Verify that the same lock object is used in both methods, e.g. if your lock statement is locking on a variable that is thread local, it won't work.
object _guard = new object();
void threadMethod1()
{
lock(_guard) {...} //data is modified inside
}
void threadMethod2()
{
lock(_guard) {...} //data is modified inside
}
not like this:
void threadMethod1()
{
lock(new object()) {...} //data is modified inside
}
void threadMethod2()
{
lock(new object()) {...} //data is modified inside
}
2 Depending on the .NET version you are using, there might be no need for locking if you use BlockingCollection or something from Parallel namespace.
I don't have reputation to post a comment - otherwise I would.
Locking does work, but here are common pitfalls -
What are you locking? Is it always the same instance of the dictionary? Locking on value types does not work - you just lock the box - then the other thread locks a different box. So this code is bad:
int x;
void SomeThreadedfunc()
{
lock((object)x) // does not work because x is boxed
{
x++;
}
}
However this works:
object lockX = new object();
int x;
void SomeThreadedfunc()
{
lock(lockX) // works
{
x++;
}
}
精彩评论