views:

42

answers:

1

In C#, a class field means every thread has its own instance of that object.

E.g. thread 1 will have its own instance of object a, as will object b.

So 2 users of a web application, on different PCs, should be accessing an instance field (Say a collection) under different, threads, right?

This makes me beg the question, why would I need to write code to synchronise the collection? If the collection is instance based and not shared state.

Is it only in the fact that I may have another thread attempt to read the collection as I modify its state. I say "Is it" because this is only a possible case through code I actually write? E.g. spawn one thread to read a non-synchronised collection, and use the original thread to write to the collection. Or is there any other gotcha?

I have put this in the beginner section as this seems to be a fundamental question.

Thanks

+2  A: 

In C#, a class by default does NOT have it's own instance of each object.

Class instances and threads are two separate constructs (unless a member is flagged [ThreadStatic], or some other exception). If you create instances, and then run a separate thread, it will be working on the same instances (unless the separate thread creates its own instances of objects).

Since the threads will, normally, work on the same instances (in order to share data and state), you need to synchronize them appropriately.

If the threads never share state or instances of objects, then you do not need to worry about synchronization. This is rare in practice, though - typically threads are working on some type of shared data. If each spawned thread creates its own objects, and no other threads talk to them, you can ignore synchronization.

Reed Copsey
Exactly what I was missing in my understanding. Thanks for the theory!
dotnetdev
No problem :) Glad I can help.
Reed Copsey