0

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

谁能解释一下吗?

4

2 回答 2

2

变量的初始化器[ThreadStatic]只会在初始化类型的线程上运行一次。

所有其他线程都会看到null

于 2014-06-11T20:22:30.757 回答
1

如果我没记错的话,您已将 _person 声明为ThreadStatic,这意味着您运行的第二个线程将无法访问它,因此它将为空。

于 2014-06-11T20:23:08.173 回答