private static variables in c# and thread safety

2019-06-27 07:03发布

问题:

A collegue of mine has written the following code in a multithreaded c# app...

public class1
{
     private static partialClass var1 = new partialNonStaticClass();

     public static method1()
     {
        //do something with var1
     }
}

Although var1 is private and set to a nonstatic partial class, the fact that it is static means it could be shared by all threads.
Also, no locking is performed on var1. Therefore, var1 is not threadsafe.

Just wanted someone to verify that I am correct.

回答1:

, the fact that it is static means it could be shared by all threads.

This is true. It could potentially be used by more than one thread.

Also, no locking is performed on var1. Therefore, var1 is not threadsafe.

This may or may not be true. If partialNonStaticClass is, itself, threadsafe, it's possible that locking is not required.