C#:如果从多个线程调用静态方法会怎样? [英] C# : What if a static method is called from multiple threads?

查看:36
本文介绍了C#:如果从多个线程调用静态方法会怎样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有一个同时从多个线程调用的静态方法.我的数据有没有被混淆的危险?

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:

  • 注意不要在状态可以共享后改变它(更好:使用不可变对象来表示状态,并将状态的快照放入局部变量中 - 即而不是引用 whatever.SomeData 重复,您将 whatever.SomeData 一次 读入局部变量,然后只使用该变量 - 请注意,这仅有助于不可变状态!)
  • 同步对数据的访问(所有线程都必须同步)——要么是互斥的,要么是(更细粒度的)读写器
  • 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 read whatever.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屋!

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