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

Comments

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!

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.

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.

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 https://youtubetomp3.sc/

https://stuccorepairdenverco.com/ 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.

tik tok like buy on :

With a number of fans, you can get as many likes and love reacts you want for your videos. What are you waiting for?

Office.com/Setup on :

Thanks for taking the time to share with us such a great article. I found such a significant number of fascinating stuff with regards to your blog particularly its discussion. Keep doing awesome.

Pasadena e waste removal on :

Appreciate this information and being able to learn more about this subject. Thanks for sharing. Pasadena commercial and residential junk removal

http://fortcollinsstumpgrinding.com/ on :

I agree that it is best to just not use ThreadStatic to avoid failure of results. Cheers from the number one stump grinding company in Fort Collins, Colorado.

property hunter on :

It's actually a great and helpful piece of information. I am satisfied that you shared this helpful information with us. Please stay us informed like this. Thank you for sharing.We at Propertyhunters. this is our service web site. please visit our web site. Thank you.Houses and Flats for Sale

office.com/setup on :

https://get-officecom.com/ Microsoft has introduced the latest edition of its widespread application on office.com/setup. Every three years, there’s a new variant with an upgraded user interface, a couple of new capabilities and functions, and a significant hassle needing to update many computers. But, Microsoft has made a substantial shift to their tried and true formula. Microsoft provides its monthly subscribers with a superb deal to proceed to their pricing model, correct? Well, let’s take a look at the pricing and see for ourselves, which is the best way to purchase Office. Office 365 Home is $99.99 yearly or $9.99 per month, Office Professional 2019 is $439.99, Office Home & Student 2019 is $149.99 annually or $14.99 per month and the Office 365 Personal is $69.99 annual or $6.99 per month

Office.com/setup on :

I am really very happy to visit your blog. Now I am found which I actually want. Thanks a lot for sharing a piece of wonderful information which I am looking for a longer period of time.

Jason Miller on :

Product Key is required only when you have purchased Office 2019 Offline or from a local store. This is not required when you have made the purchase online. This is easy process though but can be hard to handle for some. If you want help you can contact us, though we recommend you not to share your product key with the US or anyone. Someone might be able to phish you or scam you. office.com/setup

emma on :

Download Norton and stay securedNowadays we surf internet and we stay online on daily basis, and in the process we surf many websites and come across various types of ads and links. And without any knowledge we click on such malicious links and that is the time when we need and antivirus to protect our online identity. norton.com/setup

Fit Jackets on :

Thanks for sharing this, here i want to say that, I am Stephanie Shaw, my company provides best leather jackets in town.

fortcollinsdeckbuilder.com on :

Thank you for sharing this workaround. I prefer not to use ThreadStatic but with your help, I might just take the risk.

towtrucktownsville.com.au on :

Thank you for your thoughts and for organizing a great website. I'm pretty much please with your good work.

Office.com/setup on :

Thank you very much for providing this important information. I am also a writer and I have written many blogs if you want to see click here.

Office.com/setup

office.com/setup on :

https://www.officesetup-officecomsetup.com/

For people with a need for Productivity, That is every day and the general public. The office is one of the best tools to work with. This is easy and yet the most powerful productivity tool that can turn your productivity problems to dust within no time. Many offices and businesses are regular customers for the Microsoft Office Productivity tool.

norton.com/setup on :

If you are using internet or not on your device there always will be a need for strong antivirus to be installed to protect it against mischievous youths looking for a thrill or a hardened cyber-criminal wanting to take advantage of billion-dollar firms, can stop wanting to search out ways in which to commit fraud, cause widespread harm, or simply leak or use your personal data.

Office setup on :

Office 365 can be more useful than just an email application if you pick the right subscription plan. For business, enhancing productivity and collaboration in the organization has become necessary to make it easy and more proficient for the employees to work.But, numbers of businesses are still utilizing the basic plans of Office 365, which limit them from utilizing the updated features. So, to ensure you get every feature and use your Office 365 subscription to the most. office.com/setup

norton.com/setup on :

norton.com/setup Norton Security Standard can protect only one system. Norton Security Deluxe can be used for up to 5 systems, and Norton Security Premium can protect up to 10 systems. To know more about them and their comparison you can visit the official site of Norton. https://nortonn-norton.com/

norton.com/setup on :

Norton Security Standard can protect only one system. Norton Security Deluxe can be used for up to 5 systems, and Norton Security Premium can protect up to 10 systems. To know more about them and their comparison you can visit the official site of Norton. https://nortonn-norton.com/

norton.com/setup on :

href="https://nortoncomset-up.com/">www.norton.com/setup In the event that you are utilizing web or not on your gadget there consistently will be a requirement for solid antivirus to be introduced to ensure it against devilish young people searching for a rush or a solidified digital criminal needing to exploit billion-dollar firms, can quit needing to look out manners by which to perpetrate misrepresentation, cause far reaching hurt, or basically break or utilize your own information.

Add Comment

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