开发者

locking on dictionary of structs not working between 2 threads?

开发者 https://www.devze.com 2023-02-04 16:36 出处:网络
C#, .Net2.0, XP, Zen I have 2 thr开发者_开发知识库eads accessing a shared dictionary of structures, each thread via an event.

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:

  1. 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++; 
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消