private static variables in c# and thread safety

南楼画角 提交于 2019-12-23 12:15:18

问题


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.



来源:https://stackoverflow.com/questions/19144842/private-static-variables-in-c-sharp-and-thread-safety

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!