Threading question

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?
 
M

Michael D. Ober

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.
 
J

Jon Skeet [C# MVP]

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
 
G

GeezerButler

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.
 
M

Michael D. Ober

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top