【发布时间】:2014-06-11 20:20:22
【问题描述】:
我有以下测试程序,其中我使用 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);
}
}
}
谁能解释一下?
【问题讨论】:
-
你在哪一行得到了异常?
-
NullReferenceException 错误总是由同一件事引起:您试图取消引用包含
null的对象变量。 -
@RobertHarvey:在这种情况下,原因更加微妙。
-
@SLaks:你的意思是他没有试图取消引用包含 null 的对象变量?
-
@RobertHarvey:他试图取消引用一个对象,该对象 (1) 在其声明中具有非 null 初始化程序并且 (2) 从未显式分配给。在正常情况下(即没有
ThreadStatic),这种组合永远不会导致 NullReferenceException。
标签: c# nullreferenceexception thread-static