.Net: Static classes and multithreading?

I was told that in multi-threaded programs we have problems with static classes.

Could you explain this more?

+4
source share
2 answers

If static classes have any static state (for example, "global" variables), it is used for all threads. If the programmer is not careful, problems will arise with these classes. There is more, but this is the essence of it.

+3
source

In multi-threaded programs, you may have problems with anything, not just static classes. When it comes to multithreading, the main problem is usually related to data content ... in other words: ensuring proper operation when reading or writing to a shared resource. Static classes have some problems, but also have some potential advantages:

Call

  • By default, some data is displayed directly as a member variable or indirectly through an accessor / mutator, so resource protection becomes more complex.
  • Anyone using a static class can cause multithreading problems if they use the correct synchronization.

Benefit

The potential benefit is that if the static data is persistent, then there is no need for synchronization, since the data can only be read unwritten. A popular example is the Singleton class, which uses a static instance, and the instance is initialized only once, so there is no need to synchronize the Singleton instance. You may still need to synchronize the data contained in

Singleton

instance

0
source

Source: https://habr.com/ru/post/1316003/


All Articles