我有以下测试程序,其中我使用了一个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);
}
}
}
谁能解释一下吗?