user2108946
user2108946

Reputation: 41

private static variables in c# and thread safety

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.

Upvotes: 4

Views: 576

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564333

, 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.

Upvotes: 4

Related Questions