I have noticed the following statement in most places of .Net framework documentation.
Question: What is the secret to this? I don't think a static class is always thread-safe. My question relates to standard classes that are available in .Net framework, and not the custom classes created by developers.
Would the method 'GetString' in static class below be thread-safe just because the method is a static method?
public static class MyClass
{
static int x = 0;
static MyClass()
{
x = 23;
}
public static string GetString()
{
x++;
return x.ToString();
}
}
The framework methods you mention are not thread-safe just from the fact they are static, but because they have been specifically designed to be thread-safe. Thread-safety is often hard to achieve, but it's usually necessary for static methods, since any state they mutate is shared between threads.
The sample method you posted isn't thread-safe, because it mutates state that is shared between threads, without any synchronization mechanism.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With