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!

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

Mcafee.com/activate 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.

broomfieldlandscaping.com on :

Thank you for making us aware of how tedious ThreadStatic is. By the way, please visit us for landscaping services in Broomfield, Colorado.

macfee.com/activate on :

McAfee antivirus is world known antivirus for PC, Mac, Tablet and mobile. Over the last 30 years, while securing your devices against viruses, malware, fileless attacks, and other threats at home and away, McAfee has built a rich and widespread global threat intelligence network. This foundation allows us to constantly analyze and gather data on threats from over 500 million endpoints across the globe. McAfee use security analytics, cloud security, SIEM, and machine learning to allow protection, detection, and correction to happen simultaneously from device to cloud. Our endpoint protection, cloud access security broker (CASB), and McAfee ePolicy Orchestrator products are united to provide orchestration across the entire threat defense lifecycle.

Bitcoin Casino on :

I am really impressed with the information you provide in your post. Looking forward to visiting more.

Aol Login on :

AOL.com Mail login screen help - How to correctly and safely sign in to your AOL email account inbox page and how to reset AOL password.

norton.com/enroll on :

Norton Antivirus helps secure your gadgets and helps to protect and protect your data from the inevitable. How to install Norton on your PC.

norton.com/enroll

www.norton.com/setup on :

Norton is a good antivirus that protects the system from online viruses and malware. Norton Antivirus is very easy to use. Users can download, install and activate it by Norton Setup.

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.

norton.com/setup on :

Norton products are very effective for Internet threats. However the installation process of the Norton product is still easy for non-technical people or beginners find some obstacles with the install process.

roku.com/link on :

Roku is a package of entertainment. The Roku channel is the Expansion of programming for new generation children. Roku Roku declares plans to Combined kids and family movies and TV together with the channel's other content, including subscriptions, its free, television, ad-supported movies, and live TV. After the launching of "Kids & Family" section on Roku channel, Roku is also adding new features to give more control to parents over the channel, what their kids can watch when accessing Roku channels.

techjv on :

Roku is a streaming device, which provides the simplest way to stream entertainment channel to your TV. On your terms. You can access more than 500000+ movies and TV episodes across free and pay on Roku. Also, you will get the best quality video streaming with it. You can watch shows, movies, an entertainment channel, web series, etc.

ryan jack on :

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. download hulu We provide information regarding Hulu Activation Code. To activate a new Hulu account using an existing email account and you can stream television shows and movies from the Hulu site using the Hulu activation link.

Online Assignment Help UK on :

Assignment Writing Ace is the leading firm that provides an opportunity for students of all level to avail our online assignment writing services through the most experienced and professional assignment writers. These writers are equipped with the right tools to provide all kind of writing services without any limitations. Their experience in the relevant field helps them to produce a premium writing quality for our customers.

GARY DELLABITI on :

Thank you for this post. Found it very informative.

GARY DELLABITI on :

Thank you for this post. Found it very informative. https://www.treeremovalserviceyonkers.com/

Assignment Help Wales on :

Get Assignment Writing Help, Essay Writing Services, Dissertation Help, Thesis Help in Wales at Affordable Prices. Our Writers Providing Plagiarism-free Academic Paper Writing Services.

Perl Assignment Help on :

TreatAssignmentHelp is dedicated to provide online Perl Assignment Help for students who is perusing degree or diploma courses in universities. We have 24/7 Customer live support where you can discuss about your troubles with our specialized writers. We pioneer the custom writing industry due to the flair and subject expertise of our pool of writers who promise to deliver 100% plagiarism free papers.

Biology Dissertation Help on :

EssayTypist is the leading biology dissertation help that is gaining worldwide acclamation due to the ability to deliver top rated critical assessment.

Hulu Login on :

Entertainment can be more fun with Hulu as here you get access to a world full of your favorite TV shows. Here will get the opportunity to enjoy the latest content that you can stream in any of your devices supporting the app. Get your free trial and access to your device in the

Garmin.com/Express on :

Garmin Express is an extremely versatile software application available for both Windows and Mac devices. However, you are required to check the specified requirements and ensure your system conforms to it. This is extremely important for flawless setup and unmatched performance.

Garmin.com/Express on :

The software gives you desktop notifications and step-by-step instructions so that you can update your devices with ease. Even if your application is not open or the device is not connected to your system, it will give you alerts on a regular basis. So for garmin.com/express setup, you need to follow all the full-proof steps given below.

Linksys Router Login on :

The Linksys router web interface is the place where all the router settings are stored for example connectivity, wireless, security, etc. For making changes to the default settings, you need to login to your Linksys router. Also, you can change your router password after signing into your account. Once you have logged in, you will be able to adjust all the available settings according to your preference.

Webroot.com/safe on :

The more we are becoming tech-savvy, the more we need the cybersecurity. It becomes important to remain protected against all the existing and emerging online threats as they can damage your system and can also steal your data. For getting protection, you must need a comprehensive and ultimate security solution. Webroot.com/safe is one such software that can provide world-class security solutions to provide you and your device with outstanding protection

Garmin.com/express on :

Garmin.com/express is a computer application for easily setting up, registering and managing your Garmin device. The software gives you alerts whenever there are new updates available so that you can install them easily. You can also save multiple maps and preferred places with Garmin Express.

AOL Mail on :

An extensively famous and adored web-based email service, AOL Mail is now a renowned name. The mail service has gained its major fan following because of the fastest interface and features that are user-friendly. You need to choose this platform because here, you get convenient access to your emails and also enjoy several features that are brilliant.

Webroot Download on :

Among all this, Product Activation Key is the most important requirement for Webroot Download. This 20-digit reference code combines a unique set of alphanumeric characters that identifies your Subscription Terms. You can get this code only after purchasing the preferred version of this software. This implies that you must purchase a Subscription.

Office.com/setup on :

Your Microsoft Office retail card or the receipt you purchased comes with an alphanumeric product key. If the activation key does not come with your product package, you should contact your retailer or Microsoft support in the correct manner.Nevertheless,

http://www.carpetcleanergrandrapids.com/ on :

The ThreadStatic creates isolated versions of the same variable in each thread that is why it is tricky to use. I think I will try your pseudocode. Thank you for sharing.

BITCOIN LOGIN on :

I really happy found this website eventually. Really informative and inoperative, Thanks for the post and effort! Please keep sharing more such blog.

bitcoin login

bitcoin signin

aolmail.com

mcafee.com/activate

norton.com/setup

roadrunner email login

Aol Mail login on :

AOL mail login via www.aol.com/mail is an important part of receiving services that are provided by AOL. Without creating and logging in to your AOL account.

HBOGO.com/Activate on :

Here I will guide you how to activate HBO GO using hbogo.com/activate easily on Roku, Apple TV, PS4, Xbox One and other smart TVs.

ToniTohid on :

Thanks for your nice post. I am gonna to gate your post. Now a days it is very helpful and informative. I suggest every one to gate suggestion form your post. one the other hand i know a site it could help any one It is a slang and abbreviation, an abbreviation for'eat and 먹튀', and refers to a case of leaving without paying a fair price or making profits먹튀

Add Comment

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