0

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 ?

Tripp Kinetics
  • 5,178
  • 2
  • 23
  • 37
ShrShr
  • 389
  • 3
  • 10
  • 6
    On which line do you get the exception? – Tripp Kinetics Jun 11 '14 at 20:21
  • 1
    NullReferenceException errors are always caused by the same thing: you're trying to dereference an object variable that contains `null`. – Robert Harvey Jun 11 '14 at 20:22
  • 1
    @RobertHarvey: In this case, the cause is more subtle. – SLaks Jun 11 '14 at 20:23
  • @SLaks: You mean he's not trying to dereference an object variable that contains null? – Robert Harvey Jun 11 '14 at 20:24
  • 1
    @RobertHarvey: He is trying to dereference an object which (1) has a non-null initializer in its declaration and (2) is never explicitly assigned to. Under normal circumstances (i.e., without `ThreadStatic`), that combination would never lead to a NullReferenceException. – Heinzi Jun 11 '14 at 20:25

2 Answers2

2

The initializer of a [ThreadStatic] variable will only run once, on the thread that initializes the type.

All other threads will see null.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

If i'm not mistaked you've declared _person as ThreadStatic, which means that the second thread that your running wont have access to it, and it will be therefore null.

Derek
  • 8,300
  • 12
  • 56
  • 88