C#中的私有静态变量和线程安全 [英] private static variables in c# and thread safety

查看:145
本文介绍了C#中的私有静态变量和线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一位同事在多线程 c# 应用程序中编写了以下代码...

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
     }
}

尽管 var1 是私有的并设置为非静态部分类,但它是静态的这一事实意味着它可以被所有线程共享.
此外,没有对 var1 执行锁定.因此,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.

推荐答案

,它是静态的,这意味着它可以被所有线程共享.

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

此外,没有对 var1 执行锁定.因此,var1 不是线程安全的.

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

这可能是也可能不是.如果 partialNonStaticClass 本身是线程安全的,则可能不需要锁定.

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

这篇关于C#中的私有静态变量和线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆