c# - 在线程中设置全局变量 - C#

标签 c# .net-4.0 thread-safety

我有一个使用 HTTP 监听器编写的 HTTP 服务器,我想以某种方式将某些变量声明为可从线程内的任何位置访问。

  • 我的网络服务器类是基于实例的,所以我不能真正使用静态变量。
  • 我可以使用实例变量,因为所有代码都在一个类中,但是...我不知道。

我想到了使用字典:Dictionary</*[type of Thread ID here]*/,ThreadData> ,但我担心可能存在线程问题。 ThreadData 可能是类实例,但我可能会使用结构,具体取决于哪个更有效。

  • 如果我将字典键入线程 ID 并对其进行编程,以便一个线程在字典中请求它自己的条目,那么在访问字典时是否会出现任何与线程相关的问题?
  • 每个线程都会添加自己的条目。添加新线程项时是否必须锁定字典?如果是这样,我是否可以使用一个单独的锁对象来允许线程同时访问它们自己的数据?

使用并发字典会有优势吗?还有其他线程安全性更高的方法吗?

我目前正在使用 ThreadPool.QueueUserWorkItem .我不确定这是否为每个项目使用了一个新线程。如果没有,那么我也可以将其键入上下文。

更新:根据ThreadPool class - MSDN ,它确实重用了线程。并且它不会清除线程数据。

When the thread pool reuses a thread, it does not clear the data in thread local storage or in fields that are marked with the ThreadStaticAttribute attribute. Therefore, when a method examines thread local storage or fields that are marked with the ThreadStaticAttribute attribute, the values it finds might be left over from an earlier use of the thread pool thread.

最佳答案

一个解决方案是使用一个公共(public)静态字段,带有ThreadStatic属性:

[ThreadStatic]
public static int ThreadSpecificStaticValue;

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.

关于c# - 在线程中设置全局变量 - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15414312/

相关文章:

c# - 强制 protobuf-net 序列化所有默认值

c# - 如何序列化复杂的结构以通过 tcp/ip 发送?

.net - .NET Framework 4.0 的详细变更日志

.net-4.0 - Lambda表达式-根据对象集合中另一个属性的值设置该对象集合中一个属性的值

java - 当一个方法已经被另一个线程执行时跳过该方法

c# - Enumerable.Select 的表达式树

c# - 如何更好地将配置元素映射到应用程序对象?

c# - 标记所有正在等待长时间操作的线程

c++ - 如何创建锁定和解锁互斥锁的智能指针?

c# - 如果您仅更改值,List<T> 线程安全吗?