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
        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.

    public class ThreadStaticTest
        public void WithThreadStaticValueSetTest()
            Debug.WriteLine("Thread id: {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
            TestClass tc = new TestClass();
            Assert.AreSame(tc.GetThreadStaticValue(), "foo");
        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.


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



Display comments as Linear | Threaded

Do My Essay on :

Wonderful content! This is precisely what I was searching for, and it will be valuable later on. Much obliged!

Buy Custom Essays on :

A static variable marked with the Thread Static attribute is not shared between threads, therefore each thread gets it’s own instance of the static variable. You need to be aware that this is initialized only on the thread it’s declared on, all the threads which use value will get a variable initialized with it’s default value.

SI kaise bane on :

Thanks to this article I can learn more. Expand your knowledge and abilities.

pay for essay writing on :

To read this blog and some other blogs in the category of music we can make it a creative and ideal blog for the readers. There are some people who are interested to not reads this blog. But blog is so good.

7.49 godaddy domain renewals coupon on :

I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page!

samsung s3 mini on :

Get the best deal for Samsung Battery for Galaxy S III Mini

topic for education essay on :

Thanks for this valuable ThreadStatic field. It has been something that I have been looking for a few hours. Thanks!

1998yes on :

is one of the leading and famous womens online shopping store

Essay Writing Services on :

Read this weblog and some other blogs in the category of music we will make it a creative and best weblog for the readers. There are some people who are interested in no longer reads this web publication. However, the blog is so excellent.

Ali on :

I'm Really Impressed With Your Article, Such Great and Usefull Knowledge You Mentioned Here

sears special occasion dresses on :

Nice to see this beautiful blog! please keep sharing such type of Information with us. looking forward from your side.

192.168.l.254 on :

Hello! I'm sorry, that is not the topic! I really like your forum! Thank you, I'm with you)

villas in sharjah on :

The Microsoft Unit Testing Framework for C++ is covered through default in the Desktop Development with C++ workload.

gacha life on :

I have a series of Unit Tests that call a static class. My problem is I cannot enforce a set order for the tests to run. Please help me to fix it..

click here on :

I dont even recommend using it! It gives me a lot of a hard time.

click on :

Why wont you recommend it?

390 vs 395 on :

Very nice Disscussion. I just stumbled upon your Forum and wished to say that I have really enjoyed browsing your Forum. In any case I’ll be subscribing to your feed about forums because i want to get more info about Android Apps So I hope you write again very soon!

Jhon elton on :

Nice information shared, please visit this on :

If initialization on all threads is needed, then the field can be encapsulated by a lazy-initialized property: C#; VB.NET.

tree removal service boynton beach on :

This discussion unexpectedly takes my attention to join inside. Well, after I read all of them, it gives me new idea for my blog. thanks

Cooking madness on :

Thanks for the warning and Thanks for the code you've provided. It was a success.

Mercy Street Church on :

Thanks for the information on this, too a while to find a specific guide to this. -Mercy Street of Denver

먹튀검증 on :

The information you have posted is very useful. The sites you have referred was good. Thanks for sharing..

office movers perth on :

Apart from Dispose all methods and protected members are thread safe. This entry was posted in C#,

Odessa TX appliance repair on :

You showed me the light! A simpleton like me who repairs appliances really needed this help, so I owe you!

Government Schemes on :

Wonderful article, thanks for putting this together! This is obviously one great post. Thanks for the valuable information and insights you have so provided here.

Www.Office.Com/Setup on :

MS Office is the complete productivity suite which helps has MS Outlook application to schedule your meeting, or conference.

Www.Avg.Com/Retail on :

AVG antivirus is the software which helps in scanning the internal memory of your device to protect your device from malware and viruses.

Www.Webroot.Com/Safe on :

Webroot antivirus is the software which gives you the cloud storage facility to its customer so that you can take the backup of your valuable data.

best fencing in Colorado on :

Yeah you're correct. I tried this before and everything went nuts. I'm almost kick out from the project. Good thing it was fix by our supervisor. Anyway, thanks for sharing this caution. Also, please visit the best fencing in Colorado, by clicking the link above.

Car Detailing Markham on :

Good info on being careful using ThreadStatic in Visual Studio unit tests. I appreciate the heads up and the walkthrough.

Add Comment

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