在.net中两个线程之间共享静态变量的最佳方法是什么? 我在下面的代码片段中总结了我的问题
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace StackOverflow
{
class ThreadStaticProgram
{
static string threadStaticVariable = "";
static void Main(string[] args)
{
Console.WriteLine(" Main Thread Before {0} ", threadStaticVariable);
threadStaticVariable = " Main Thread ";
Console.WriteLine(" Main Thread Before For Loop = {0} ", threadStaticVariable);
Thread[] threads = new Thread[3];
for (int i = 0; i < 3; i++)
{
threads[i] = new Thread(delegate(object j)
{
Console.WriteLine(" Thread{0} before = {1} ", j, threadStaticVariable);
threadStaticVariable = " Thread " + j;
Console.WriteLine(" Thread{0} after ={1} ", j, threadStaticVariable);
}
);
threads[i].Start(i);
}
Array.ForEach(threads, delegate(Thread t) { t.Join(); });
Console.WriteLine(" Main Thread after For Loop = {0} ", threadStaticVariable);
Console.ReadLine();
}
}
}
问题II - 什么是线程本地存储?
答案 0 :(得分:1)
这取决于变量。如果它是一个可以原子设置的类型,则标记为volatile,和/或使用Interlocked类来更改它的值。
如果它是一个正在改变的单个引用,您可以使用Interlocked.Exchange以原子方式执行此操作。
否则,您可能希望使用某种形式的同步。可以用锁包装的私有静态对象是最常见的选项,但它确实取决于。如果它是一个集合,使用ConcurrentQueue<T>
和类似的删除需要锁。