> To prevent concurrent access to a data structure, one way is to use its
> Synchronized method, another way is to use unlock keyword in C#. I'd like to
[quoted text clipped - 16 lines]
>
> What's the difference between this two methods? Thanks!
I would personally recommend locking, but not on "this". Using the
synchronized wrappers only makes each operation synchronized - you
still have to lock (on the SyncRoot) for any sequence of operations you
want to be atomic (such as iterating through the list).
See
http://www.pobox.com/~skeet/csharp/multithreading.html#lock.choice for
more about choosing what to lock on.

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Lei Jiang - 28 Jul 2004 09:28 GMT
Thanks!
> > To prevent concurrent access to a data structure, one way is to use its
> > Synchronized method, another way is to use unlock keyword in C#. I'd like to
[quoted text clipped - 25 lines]
> http://www.pobox.com/~skeet/csharp/multithreading.html#lock.choice for
> more about choosing what to lock on.
>To prevent concurrent access to a data structure, one way is to use its
>Synchronized method, another way is to use unlock keyword in C#. I'd like to
>know how to choose from them.
Easy. Don't use Synchronized, ever. Always use lock (list.SyncRoot).

Signature
http://www.kynosarges.de
Lei Jiang - 28 Jul 2004 09:29 GMT
Thanks. But why?
> >To prevent concurrent access to a data structure, one way is to use its
> >Synchronized method, another way is to use unlock keyword in C#. I'd like to
> >know how to choose from them.
>
> Easy. Don't use Synchronized, ever. Always use lock (list.SyncRoot).
Christoph Nahr - 28 Jul 2004 12:35 GMT
>Thanks. But why?
Because Synchronized only gives the illusion of thread safety.
For example, the following code is NOT thread-safe:
ArrayList list = new ArrayList();
ArrayList syncList = ArrayList.Synchronized(list);
...
int index = syncList.IndexOf(foo);
if (index >= 0) syncList[index] = bar;
Between calling IndexOf and changing the object at index, another
thread might jump in and change the contents of syncList. This is
possible because Synchronized protects only individual operations, not
sequences of two or more operations.
By contrast, the following code IS thread-safe (provided all other
threads also call lock (list.SyncRoot) before accessing the list):
lock (list.SyncRoot) {
int index = list.IndexOf(foo);
if (index >= 0) list[index] = bar;
}

Signature
http://www.kynosarges.de
Lei Jiang - 29 Jul 2004 02:25 GMT
Thanks. I see .
> >Thanks. But why?
>
[quoted text clipped - 19 lines]
> if (index >= 0) list[index] = bar;
> }