How does the lock statement work?

  • Thread starter Hans Olav Stjernholm
  • 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.
 
J

Jon Skeet [C# MVP]

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.
 

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