Locking the object is fine.
If you were thinking of using:
lock(this)
You should know that because you're looking on your instance, users of your
class could also lock on it and screw you up. Whether or not that is an
issue depends on what you think your users might do. The same situation
exists if you're doing:
lock(typeof(MyClass))
If you don't want to do this, you can easily allocate a static or instance
object (ie object myLock = new object()), and then lock on that.
--
Eric Gunnerson
Visit the C# product team at
http://www.csharp.net
Eric's blog is at
http://weblogs.asp.net/ericgu/
This posting is provided "AS IS" with no warranties, and confers no rights.
"Rich Sienkiewicz" <an*******@discussions.microsoft.com> wrote in message
news:E6**********************************@microsof t.com...
Thanks for the reply guys. But I'm more confused. I should not lock the
instance like this:
lock(sl)
but lock the SyncRoot, like this?
lock(sl.SyncRoot)
But the help system (C# Programmer's Reference) describing the lock
statement says "The lock keyword marks a statement block as a critical
section by obtaining the mutual-exclusion lock for a given object, executing
a statement, and then releasing the lock." It never mentions the SyncRoot,
just lock the instance itself.
The help system is misleading then in talking about the Synchronized
method. It says, for the SortedList.Synchronized method, "Returns a
synchronized (thread-safe) wrapper for the SortedList.". Then in the Remarks
section it says "To guarantee the thread safety of the SortedList, all
operations must be done through this wrapper only." That to me says get and
use the wrapper for thread safety. If this is not true then this must be
reworded, no?
So my question remains, if I have one thread iterating over a SortedList
and another thread can come along and add/delete an item from it, what
should each thread do to the SortedList, lock or Synchronize?
Thanks,
Rich