How does the lock statement work?

  • Thread starter Thread starter Hans Olav Stjernholm
  • Start date Start date
H

Hans Olav Stjernholm

Hi!

I'm using C# and have done a bit of reading about the synchronization
mechanisms in .Net.
My understanding is that a lock on an instance object makes sure that no
other threads can access the object while locked.

lock (myObj)
{
}

I have my own collection and use lock inside the Remove and Add methods. My
question is this: Is it thread safe to enumerate through the collection
without a lock the collection?

foreach (object obj in myCollection)
{
}

Or do I have to suffer a lock on the object here also?

Any answers and elaborations are really welcomed!!!

Regards,
Hans Olav.
 
Hans Olav Stjernholm said:
I'm using C# and have done a bit of reading about the synchronization
mechanisms in .Net.

Have a look at http://www.pobox.com/~skeet/csharp/multithreading.html

I believe it answers your questions about locking.
I have my own collection and use lock inside the Remove and Add methods. My
question is this: Is it thread safe to enumerate through the collection
without a lock the collection?

foreach (object obj in myCollection)
{
}

Or do I have to suffer a lock on the object here also?

The point is to lock the collection for the *whole* of the enumeration
(so that other things can't add/remove items between iterations or the
enumerator), which means it can't be done within any method of the
collection itself.
 
Back
Top