Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are static methods in .Net framework classes always thread-safe?

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.

Thread Safety Note in all .Net Framework Classes documentation

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();
    }
}
like image 367
Sunil Avatar asked Dec 15 '22 20:12

Sunil


1 Answers

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.

like image 53
Thomas Levesque Avatar answered May 10 '23 19:05

Thomas Levesque