C#中:如果静态方法是从多个线程叫什么? [英] C# : What if a static method is called from multiple threads?
问题描述
在我的应用我有一个从多个线程在同一时间被称为静态方法。有没有我的数据的任何危险混合了?
In my Application I have a static method that is called from multiple threads at the same time. Is there any danger of my data being mixed up?
在我第一次尝试的方法是不是静态的,我创建了一个类的多个实例。在这种情况下,我的数据得到了某种程度上混淆。我不知道这是如何发生,因为它只是有时会发生。我还在调试。
但现在的方法是静态的对我没有问题为止。也许这只是运气。我不知道。
In my first attempt the method was not static and I was creating multiple instance of the class. In that case my data got mixed up somehow. I am not sure how this happens because it only happens sometimes. I am still debugging. But now the method is static on I have no problems so far. Maybe it's just luck. I don't know for sure.
推荐答案
方法内声明的变量(有可能是个例外抓获的变量)是孤立的,所以你不会得到任何内在问题;但是,如果你的静态方法访问的共享状态,全盘皆输。
Variables declared inside methods (with the possible exception of "captured" variables) are isolated, so you won't get any inherent problems; however, if your static method accesses any shared state, all bets are off.
共享状态的例子是:
- 静态字段
- 从一个共同的高速缓存访问的对象(非序列化)
- 数据,如果有可能是多个线程都在触摸同一对象(多个)
经由输入参数(和状态对这些对象)中获得
如果您有共享状态,你必须:
If you have shared state, you must either:
- 要注意不要发生变异的状态,一旦它可以共享(最好:使用不可变对象重新present状态,并采取状态的快照到一个局部变量 - 例如,而不是参照
whatever.SomeData code>反反复复,你读
whatever.SomeData code> 曾经到一个局部变量,然后只使用变量 - 注意,这不仅有利于对不可变状态)
- (所有线程必须同步)同步到数据存取 - 无论是互斥或(更精细)读/写器
- take care not to mutate the state once it can be shared (better: use immutable objects to represent state, and take a snapshot of the state into a local variable - i.e. rather than reference
whatever.SomeData
repeatedly, you readwhatever.SomeData
once into a local variable, and then just use the variable - note that this only helps for immutable state!) - synchronize access to the data (all threads must synchronize) - either mutually exclusive or (more granular) reader/writer
这篇关于C#中:如果静态方法是从多个线程叫什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!