I have the following test program where I an using a ThreadStatic
variable, when I try this code I get a 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);
}
}
}
Can anyone explain it please ?