在我的 C#
MVC 项目中,我在一个类中有一个静态成员,它由同一类的另一个实例更新。但问题是所有拥有此类实例的线程也使用相同的内存来更新静态变量。但我不希望跨线程共享变量。
有什么方法可以让类的数据成员在同一个线程中的所有类实例之间共享,但如果在不同的线程中则创建一个新的内存位置?
最佳答案
这可能适合也可能不适合您的需求,但您可能解决此问题的一种方法是使用线程静态字段
Indicates that the value of a static field is unique for each thread.
A static field marked with ThreadStaticAttribute is not shared between threads. Each executing thread has a separate instance of the field, and independently sets and gets values for that field. If the field is accessed on a different thread, it will contain a different value
请注意,除了将ThreadStaticAttribute
属性应用于字段外,您还必须将其定义为static
public class Example
{
[ThreadStatic] static double previous = 0.0;
[ThreadStatic] static double sum = 0.0;
[ThreadStatic] static int calls = 0;
[ThreadStatic] static bool abnormal;
...
关于c# - 在同一线程中类的所有实例之间共享类的数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52182292/