-1

I was wondering what it means for a multi-threaded system to use static classes in the following ways:

  1. Without using a service:
    Multiple instances of a Class A are using the same static class B for some random calculations (eg. System.Math)
  2. Using WCF services:
    a. Having 1 single WCF service doing what is described in 1.
    b. Having several WCF services, each having 1 instance of a Class A using the same static class B for some random calculations
    c. Having several WCF services, each having more than 1 instances of a Class A, all using the same static class B for some random calculations

From what I understand, using static classes as per 2.b. is the only proper option for multi-threaded systems as each WCF service will create its own copy/instance of the static class. All the other options will share the same static class and are therefore not allowing for multi-threading.

Is that about right?

What does it mean for the other options though? Is there a way to make static classes somehow instantiable? Thinking about System.Math, I cannot really just go and edit the source code.
Or is it common practice to just cope with it by adding a lock where these static classes are being used?

Maybe a singetone should rather be used than static when possible?

stackMeUp
  • 522
  • 4
  • 16
  • 1
    What's wrong with using `System.Math` concurrently by multiple threads? This class is not storing internally mutable shared state. – Theodor Zoulias Feb 13 '20 at 13:32
  • @ Theodor Zoulias - Well, should a Multi-threaded system not actually multi-thread rather than queuing? Concurrency won't happen in most cases I listed. – stackMeUp Feb 13 '20 at 14:32

1 Answers1

-1

Static classes that have static methods without static data are generally safe. The problem it they have static data, that potentially can be changed.

See Thread-safe initialization of static variables

Michael Freidgeim
  • 26,542
  • 16
  • 152
  • 170