Threading question

  • Thread starter Thread starter GeezerButler
  • Start date Start date
G

GeezerButler

I am very new to threading.
I am having trouble deciding on which object i should obtain lock.
class MyClass
{
private ICollection<ClassB> myColl;

public void ModifyCollection()
{
lock(????)
{
//modify the collection
}
}
}

Should I obtain lock on myColl itself or should i introduce a new
private object syncRoot in my class and obtain a lock on that?
Note that ICollection<T> does not have any syncRoot member unlike
ICollection.
On the web, I could see that both these ways are used extensively.
But what would be the differences?
 
Create a new private object in your class and do the locks on it. Also, you
need to ensure that reading the collection is locked as well (in .NET 2.0
there is a reader/writer lock mechanism that allows multiple read locks but
only one write lock) to ensure that the collection read is consistent.

Mike.
 
GeezerButler said:
I am very new to threading.
I am having trouble deciding on which object i should obtain lock.
class MyClass
{
private ICollection<ClassB> myColl;

public void ModifyCollection()
{
lock(????)
{
//modify the collection
}
}
}

Should I obtain lock on myColl itself or should i introduce a new
private object syncRoot in my class and obtain a lock on that?
Note that ICollection<T> does not have any syncRoot member unlike
ICollection.
On the web, I could see that both these ways are used extensively.
But what would be the differences?

See http://pobox.com/~skeet/csharp/threads/lockchoice.shtml and
http://pobox.com/~skeet/csharp/threads/alternative.shtml
 
Create a new private object in your class and do the locks on it. Also, you
need to ensure that reading the collection is locked as well (in .NET 2.0
there is a reader/writer lock mechanism that allows multiple read locks but
only one write lock) to ensure that the collection read is consistent.

Mike.








- Show quoted text -

Thanks for replying.
But can you explain why you'd prefer locking on the private object
rather than the collection itself.
 
I usually use a SynchronizationObject to make my code more readable. In
addition, without knowing the specific locking mechanism (I have
disassembled the generated IL) and knowning that many of the synchronization
classes have direct counterparts in the Win32 API, I assume that the
framework will use the underlying Win32 API for performance reasons.

Mike.
 
Back
Top