Access to class member by multi threads

Viewed 39

I made a class (parent class) with several variables on it. This class is accessed by multiple threads. However, each variable is accessed by only a dedicated thread.

I was wondering, when a thread accesses a dedicated variable, this thread locks the parent class or it just locks the accessed variable?

1 Answers

There is no implicit locking in c#. If you need to lock something, use a lock. See also interlocked for some lower level methods that are sometimes useful.

Note that there are thread safety issues whenever there is any chance of concurrent reading and writing, or writing and writing, of memory. Easiest way to avoid this is to ensure there is no writing going on, i.e. use immutable objects and pure functions.

While your design sound safe since there is no concurrent read/writes to any single field, it is terrible usability, since the caller needs to follow some special rules.

By convention, static methods should be thread safe, while non static methods should be assumed non thread safe, unless otherwise specified.

  • If a class is thread safe, any methods should be callable from any thread at any time.
  • If a class is not thread safe, none of its methods should be used concurrently.

Also note that multi threaded programming is difficult. It is very easy to introduce bugs that only appear in very special circumstances, and therefore difficult to find. So I would recommend reading a fair bit about multi threading and thread safety before using any kind of multi threading for anything important.

Related