我已经创建了3个线程,并且所有线程都在线程列表属性上具有增量操作,除了thread1。我还以图11的值初始化ThreadLocal委托中的线程属性。在这里,我总是在第一个线程中获得num = 0的值。为什么呢?
class Program
{
//static int numDuplicate = 0;
[ThreadStatic]
static int num = 5;
public static ThreadLocal<int> _field = new ThreadLocal<int>(() =>
{
num = 11;
//numDuplicate = num;
Console.WriteLine("Threadstatic variable value in Threadlocal's delegate = " + num.ToString());
return Thread.CurrentThread.ManagedThreadId;
});
public static void Main(string[] args)
{
Thread t1 = new Thread(new ThreadStart(() =>
{
Console.WriteLine("Threadlocal attribute value for thread 1: " + _field + ". Threadstatic variable value = " + num.ToString());
}));
Thread t2 = new Thread(new ThreadStart(() =>
{
_field.Value++;
Console.WriteLine("Threadlocal attribute value for thread 2: " + _field + ". Threadstatic variable value = " + num.ToString());
}));
Thread t3 = new Thread(new ThreadStart(() =>
{
_field.Value++;
Console.WriteLine("Threadlocal attribute value for thread 3: " + _field + ". Threadstatic variable value = " + num.ToString());
}));
t1.Start();
t2.Start();
t3.Start();
Console.ReadLine();
}
}
//Output:
Threadstatic variable value in Threadlocal's delegate = 11
Threadstatic variable value in Threadlocal's delegate = 11
Threadstatic variable value in Threadlocal's delegate = 11
Threadlocal attribute value for thread 1: 10. Threadstatic variable value = 0
Threadlocal attribute value for thread 3: 13. Threadstatic variable value = 11
Threadlocal attribute value for thread 2: 12. Threadstatic variable value = 11
,因为'不能为线程构图分配一个初始值。
请勿指定用线程构图标记的字段的初始值,因为当类构造函数执行时,这种初始化仅发生一次,因此仅影响一个线程。如果您不指定初始值,则可以依靠该字段(如果是值类型),或者如果是参考类型,则可以依靠其默认值。
。
来源:MSDN
您可以看一下ThreadLocal<>
static ThreadLocal<int> num = new ThreadLocal<int>(() => 5);
Func<>
将作为for foreach新线程执行。在这种情况下,它只是返回5。