c# - 在同一线程中类的所有实例之间共享类的数据成员

标签 c# asp.net-mvc controller static thread-safety

在我的 C# MVC 项目中,我在一个类中有一个静态成员,它由同一类的另一个实例更新。但问题是所有拥有此类实例的线程也使用相同的内存来更新静态变量。但我不希望跨线程共享变量。

有什么方法可以让类的数据成员在同一个线程中的所有类实例之间共享,但如果在不同的线程中则创建一个新的内存位置?

最佳答案

这可能适合也可能不适合您的需求,但您可能解决此问题的一种方法是使用线程静态字段

ThreadStaticAttribute Class

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/

相关文章:

c# - 来自 WebAPI 的服务器调用图像

javascript - 在循环中注册启动脚本

c# - 声音错误(MonoGame)

jquery 使用 asp.net MVC 部分 View 加载

asp.net - 如何自定义 ASP.NET Web API AuthorizeAttribute 以满足异常需求

c# - 无法将类型 'System.Linq.IQueryable<int>' 转换为 'int'

java - 使用 Spring Boot 自动转换 RequestBody 期间,ZonedDateTime 的时区更改为 UTC

javascript - 在单页应用程序中使用 AngularJS 的多个 Controller

C# 和 VB6 : How to convert 'with' statement to C#?

c# - 如何在它调用的 asmx 中获取对 Page 对象的引用