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

click site on : click site

Show preview
blog topic

Comments

Display comments as Linear | Threaded

www.Norton.com/setup on :

Norton.com/setup – Talking about antivirus program, Norton is the best option available in the market. Norton Antivirus is an effective anti-malware scanning engine that is reliable.

www.office.com/setup on :

The latest Office edition available is Office 2019. One can access the complete details about the product via office.com/setup.

www.Hulu.com/Activate on :

Create an account and generate activation code by Hulu.com/activate after this you can use your device and watch your series, movies, shows etc.

www.trendmicro.com/downloadme on :

You can download any of the TrendMicro version from the www trendmicro com downloadme URL. Either your device is new, or you bought it previously, each device requires threat and virus protection from any of the antivirus.

www.malwarebytes.com/mac on :

Malwarebytes is anti-malware software also a good replacement for antivirus in Mac computer. It protects Mac computer from all kind of bad infection which is coming from the Internet like (Viruses, Spyware, Malware, Adware, Ransomware, etc.)

www.mcafee.com/activate on :

Download and install McAfee antivirus using simple steps given in this article. You need a McAfee account and a 25 digit McAfee activation code to complete the process. To activate McAfee antivirus software for your computer & pc, enter Mcafee activation code on Mcafee activate. After activation, you can download, install, reinstall Mcafee product.

mcafee.com/activate on :

Thanks for writing such a good article, I stumbled onto your blog and read a few posts. I like your style of writing.

install malwarebytes already purchased on :

Thank you for sharing your info. I really appreciate your efforts and Thanks a lot for sharing a piece of wonderful information which I am looking for a longer period of time.

malwarebytes.com/install on :

Great, thanks for the information. It was really in search of this type of knowledge. Helpful to me at least!

Trash Removal on :

Appreciate you sharing this piece of code as it seems to be very helpful. Thank you.

roku.com/link on :

Roku. Inc provides the best in quality streaming experience, which will make your moments more enjoyable.

emergency tree removal on :

Thank you for sharing this post. If you need emergency tree removal in Loveland, Colorado then contact us now.

www.malwarebytes.com/mac on :

Before Starting with Malwarebytes Anti-malware user’s need to check and identify Malwarebytes Anti-malware key code,

webroot.com/safe on :

At one point the Webroot safe console will ask for key code put your webroot key code

Norton.com/setup on :

In the digital world where we live today, computers, smartphones, tablets, and other devices have become requirements.

John on :

Complete the Roku activation process after entering the activation code in Roku.com/link page. Call us to get help in activating the Roku.

ryan jack on :

Hulu.com/activate - Watch your favorite live sports, news, entertainment, and more. Plus, get unlimited access to the entire Hulu streaming library. To activate Hulu code go to url if you need help to activate Hulu then contact Hulu provides the simplest way to stream entertainment to your T.V. On your terms. With thousands of available channels. We provide information regarding Hulu Activation Code.hulu.com/activate.

Norton.com/setup on :

Norton.com/setup is an Antivirus software that provides user security and guards their essential information and necessary details from the Hackers so that they can stay protected from the thefts.

arvadaconcrete.org/ on :

ThreadStatic is tricky but totally worth the complexity. I am so thankful for this post.

www.roku.com/link on :

Roku is a small class tool that lets you view free and paying video content over the Internet on your TV.

www.roku.com/link

roku com/link on :

The Roku Device No.1 is a streaming device that is very popular in the United States all over the world. Roku provides users with the best entertainment they have ever wanted. You can turn your computer on very quickly in easy steps.

roku.com/link on :

Roku is an official link that helps user to activate their roku device or TV. In order to activate roku tv or device, user should have roku activation code.

roku.com/link on :

Roku activation code is an alpha numeric code which helps users to enable their roku device or tv. If the activation phase has been completed, computer would require them to display their fav stuff online at one place.

roku.com/link on :

If you are a new user with Roku and want to setup your Roku Device, then you can follow the guidelines which is listed with user guide which you received with your purchase. If you are not able to find the user guide then search for step by step Roku device setup or Installation guide.

Mcafee.com/activate on :

It’s truly a great and useful piece of info. I’m happy that you just shared this useful information with us. Please keep us up to date like this. Thanks for sharing.

USD to MXN on :

Ich danke Ihnen für die Information! Ich war auf der Suche nach und konnte nicht finden. Du hast mir geholfen!

Concrete Additions on :

This is a great article. The main idea behind ThreadStatic is to maintain a separate copy of the variable for each thread.

NguyenSmith on :

After purchasing a Roku device you must search for roku.com/link on the search engine. then click on the link below. and get started with Roku account creation. and find Roku activation code, link and activate Roku devices and channels on Roku from roku.com/link using the available link, you need to click on the appropriate link to activate the Roku streaming.

roku.com/link on :

Roku activation code is used at www.roku.com/link or roku.com/link to activate roku device. Get roku support for any activation help.

roku.com/link on :

Roku devices or tv work great if you set up it correctly. Many people do it wrong and face many issues, so I am here providing a useful Roku activation guide. https://rokuomlink.com is the absolute and best way to do it easily, follow my guide and set it up correctly.

privacy fence on :

Thank you sharing your insight about ThreadStatic in Visual Studio unit tests. We will not use ThreadStatic now for sure!

cicerocarpetcleaning.net/ on :

ThreadStatic is a complex but effective technique. Let's just be keener when using this one.

download quickbook online on :

QuickBooks Online is a perfect cloud solution. that can be used on any computer (Mac and PC), tablets and any mobile device on a available browser.

download quickbook desktop on :

Enterprise version is allows maximum thirty users to work at once. And this version includes features from all versions of QuickBooks Desktop. This is the most advanced version of QuickBooks Desktop.

roku.com/link on :

Roku is the main video real-time bundle that lets us experience the new universe of amusement. It gives the client to utilize numerous different applications which makes it stand apart in an unexpected way.

123.hp.com/setup on :

HP printers are known around the world for their quality, lively printing and user-friendliness.Whenever a new printer is purchased it is important that the software required in them HP software. You need to go to the website and search for the specific software that fits your HP printer model and create it.

Capital Gains Tax Advice on :

Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained!

WordPress Speed Optimization on :

Google started using site speed as a ranking signal in their algorithm way back in 2010, and it continues to serve as one of the many factors that determine where your website shows up in the search results. We help you WordPress Speed Optimization are Page Caching, PHP latest version, Image optimization and resizing, jquery update, Cache Preloading, Sitemap Preloading, GZIP Compression, Browser Caching, Database Optimization, Google Fonts Optimization, Lazyload, Minifying JS CSS HTML files, Deferring Unused JS/CSS, CDN setup, Mobile Detection, Stop unused CSS and JS file and many more optimization your WordPress website. So, your website super-fast loading within 1-5 seconds.

Add Comment

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