简体   繁体   English

声明为另一个类的静态成员的类对象的方法的线程行为

[英]Threading behavior of methods of a class object declared as static member of another class

Recently a colleague of mine came up with a piece of code and asked my opinion regarding thread safety of the code. 最近,我的一位同事提出了一段代码并询问了我对代码的线程安全性的看法。 Below is an example that illustrates the same scenario as the code. 下面的示例说明了与代码相同的方案。

public class classA
{
   public int DoWorkA() 
   { 
       //some logic 
   }
}

public class classB
{
     public static classA objA = new classA();
}

public class classC
{
        int DoWorkC () 
        {

           return classB.objA.DoWorkA();

        }
}

Now if ClassB.objA.DoWorkA() is called simulatenously in different instances of different classes like ClassC, ClassD etc will there be any threading or 'overlap' issues ? 现在如果在ClassC,ClassD等不同类的不同实例中同时调用ClassB.objA.DoWorkA()会有任何线程或“重叠”问题吗? Should objA be converted into an instance member ? objA应该转换为实例成员吗?

Since objA is static there will be just a single instance of classA . 由于objA是静态的,因此只有一个classA实例。 That means all threads access the method DoWorkA() on the same instance , it does not mean however that the method call is thread-safe - that entirely depends on the implementation of DoWorkA() . 这意味着所有线程都在同一个实例上访问方法DoWorkA() ,但这并不意味着方法调用是线程安全的 - 这完全取决于DoWorkA()的实现。

You will still need appropriate logic in DoWorkA to protect from problems that can arise with concurrent access, eg the use of locking or thread-safe collections etc. 您仍然需要在DoWorkA适当的逻辑来防止并发访问可能出现的问题,例如使用锁定或线程安全集合等。

will there be any threading or 'overlap' issues 会有任何线程或“重叠”问题

It depends on what //some logic does. 这取决于//some logic作用。 Each call will share the same instance, so DoWorkA would need to be thread safe in order for this to function correctly. 每个调用都将共享同一个实例,因此DoWorkA需要是线程安全的才能使其正常运行。

Any data used within //some logic needs proper synchronization for this to be safe. //some logic使用的任何数据都需要正确同步才能确保安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM