Static is often used in C# to refer to Static variables and methods
What’s the difference between a static variable and an instance variable?
- 1. Syntactically: static variables are preceded by the Stati keyword, while instance variables are not.
- 2. Runtime: static variables will be allocated space when the program runs, while instance variables belong to the attributes of an object, which need to create the instance object will be allocated space.
- 3. Storage area: Static variables are stored in static storage, and ordinary variables are stored in the heap.
Static methods differ from instance methods in two main ways:
-
You can use the “class name” when calling static methods externally. Method name, or object name. Method name “. Instance methods have only the latter. That is, you can call a static method without creating an object.
-
When a static method accesses a member of the class, it only allows access to a static member (that is, static member variables and static methods), but not to instance member variables and instance methods. Instance methods do not have this limitation.
Static method thread safety issues
Briefly discuss whether using static fields and static methods in a class is a thread-safe issue.
Static fields and static methods are called by classes. Static methods do not operate on specific instances and can only access static members. Instance methods can operate on specific instances and access both static and instance members.
So, is there a thread-safety issue with using static methods in multiple threads? It depends on whether static methods raise thread-safety issues and whether static members are used in static methods.
When using the same static method in multiple threads, each thread uses its own copy of the instance field and shares a static field. So, if the static method does not operate on a static member, using only the instance field inside the method does not pose a security problem. However, if the static method operates on a static field, you need to secure it with mutually exclusive access in the static method.
For a simple example, we use console.writeline (); WriteLine() is a static method of the console. WriteLine class.
Static methods that do not use static variables do not have thread-safety issues. Why is that? Each thread creates a new copy of a variable declared in a static method, rather than sharing a single storage unit. In TMP, for example, each thread creates its own copy, so there are no thread-safety issues. Note: Static variables, since they occupy a storage area during class loading, are shared by each thread, so if you use static variables in a static method, this is a thread-safe issue!