Skip to content

Be careful using ThreadStatic in Visual Studio unit tests

Given is a ThreadStatic field which is set to empty in the static constructor, and set by a public instance method:

    public class TestClass
    {
        [ThreadStatic] 
        private static string threadStaticValue;
        static TestClass()
        {
            threadStaticValue = "";
        }
        public void SetThreadStaticValue(string value)
        {
            threadStaticValue = value;
        }
        public string GetThreadStaticValue()
        {
            return threadStaticValue;
        }
    }

Now two unit tests check whether the threadStaticValue is set correct.

    [TestClass]
    public class ThreadStaticTest
    {
        [TestMethod]
        public void WithThreadStaticValueSetTest()
        {
            Debug.WriteLine("Thread id: {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
            TestClass tc = new TestClass();
            tc.SetThreadStaticValue("foo");
            Assert.AreSame(tc.GetThreadStaticValue(), "foo");
        }
        [TestMethod]
        public void WithThreadStaticValueNotSetTest()
        {
            Debug.WriteLine("Thread id: {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
            TestClass tc = new TestClass();
            Assert.AreSame(tc.GetThreadStaticValue(), "");
        }
    }

Those tests will fail(good) or pass(bad) depending of whether the test engine will reuse the same thread.

Executed a second time, the result could be different.

Solution:

  1. Don't use ThreadStatic at all
  2. Make sure the ThreadStatic fields are initialized correctly before using them

Trackbacks

No Trackbacks

Comments

Display comments as Linear | Threaded

No comments

Add Comment

You can use [geshi lang=lang_name [,ln={y|n}]][/geshi] tags to embed source code snippets.
Markdown format allowed
Form options