我有以下测试程序,我使用ThreadStatic
变量,当我尝试此代码时,我得到NullReferenceException
。
using System;
using System.Threading;
namespace MiscTests
{
public class Person
{
public string Name { get; set; }
}
class Program
{
[ThreadStatic]
private static Person _person = new Person { Name = "Jumbo" };
static void Main(string[] args)
{
Thread t1 = new Thread(TestThread);
t1.Start();
Thread t2 = new Thread(TestThread1);
t2.Start();
Console.ReadLine();
}
private static void TestThread(object obj)
{
Console.WriteLine("before: " + _person.Name);
_person.Name = "TestThread";
Console.WriteLine("after: " + _person.Name);
}
private static void TestThread1(object obj)
{
Console.WriteLine("before: " + _person.Name);
_person.Name = "TestThread1";
Console.WriteLine("after: " + _person.Name);
}
}
}
有人可以解释一下吗?
答案 0 :(得分:2)
[ThreadStatic]
变量的初始值设定项只会在初始化类型的线程上运行一次。
所有其他主题都会看到null
。
答案 1 :(得分:1)
如果我没有弄错,你已经将_person声明为 ThreadStatic ,这意味着你运行的第二个线程无法访问它,因此它将为null。