Here is a small programming tip I thought I would share. Sometimes in .NET / C# I find myself needing to write a pattern similar to this:

private bool m_bSemaphore = false;

private void DoSomethingCrazy()
{
   if (m_bSemaphore == false)
   {
      m_bSemaphore = true;
      //Do some crazy stuff
      m_bSemaphore = false;
   }
}

This intent of this code would be to prevent the DoSomethingCrazy() method from being executed simultaneously.  The first thread to invoke DoSomethingCrazy() would set the semaphore and all subsequent calls from other threads would be ignored until the semaphore is reset. The problem with the code above is that it is not thread safe.  It is possible two competing threads could both execute the IF clause and decide the semaphore is false at exactly the same time.  The entire point of the semaphore is to prohibit this from happening, so the code above is actually a very subtle bug waiting to happen.  Most of the time it's going to work, but there is that small chance things are going to go wonky when least expected. A more robust solution which is thread-safe would be to craft the logic similar to this:

private object m_objSyncLock = new object();

private void DoSomethingCrazy()
{
   if (Monitor.TryEnter(m_objSyncLock))
   {
      //DoCrazyStuff
      Monitor.Exit(m_objSyncLock);
   }
}

By using the .NET static Monitor class makes we make the testing of the lock (TryEnter) and the acquisition of the lock into a single atomic operation (ie. only 1 thread can do both steps at a time).  

devMash.com Pinwheelarticle copyright © 2015 devMash.com

35 Comments

  • jordans said

    I have to show thanks to you just for bailing me out of this particular dilemma. Because of browsing throughout the world wide web and meeting principles which are not productive, I believed my entire life was done. Existing without the presence of approaches to the issues you have solved as a result of your entire write-up is a critical case, as well as the kind that would have negatively damaged my career if I had not encountered your website. Your own know-how and kindness in playing with everything was precious. I don't know what I would have done if I had not discovered such a stuff like this. I can at this point look ahead to my future. Thanks a lot very much for your high quality and results-oriented help. I will not be reluctant to propose the website to any person who would like guide on this area.

  • moncler jackets said

    Thanks so much for providing individuals with an extraordinarily splendid chance to read in detail from this blog. It really is very cool and as well , full of a great time for me personally and my office colleagues to search your web site at a minimum 3 times in a week to see the fresh issues you have. And of course, I'm certainly contented with the remarkable tricks served by you. Selected 3 facts in this post are unequivocally the simplest we've ever had.

  • kd 11 said

    I wish to show some appreciation to you just for bailing me out of this particular incident. Right after exploring throughout the the net and seeing views which were not powerful, I believed my entire life was well over. Living minus the answers to the issues you've solved by means of your entire article is a crucial case, and the ones that would have in a negative way affected my career if I had not encountered your blog. Your own know-how and kindness in touching almost everything was important. I am not sure what I would have done if I hadn't discovered such a stuff like this. I am able to at this point relish my future. Thank you so much for this skilled and amazing guide. I will not be reluctant to recommend the blog to any individual who would need guidance about this situation.

  • yeezy boost 350 said

    I happen to be commenting to make you understand of the superb discovery my cousin's child went through reading your web site. She even learned lots of issues, including what it's like to possess an excellent coaching style to let many more clearly comprehend various problematic things. You actually did more than visitors' expected results. Thank you for supplying these helpful, trustworthy, edifying and as well as unique tips about your topic to Gloria.

  • nike hyperdunk said

    Thanks so much for giving everyone an extraordinarily breathtaking chance to discover important secrets from this site. It really is very cool plus jam-packed with a great time for me personally and my office co-workers to search your website at the very least thrice weekly to see the latest things you have got. And of course, we are at all times amazed with all the unique thoughts you serve. Some 4 tips in this posting are rather the most beneficial we've ever had.

  • lacoste online shop said

    I have to show some thanks to you for bailing me out of this particular instance. After surfing around through the world-wide-web and getting proposals that were not pleasant, I assumed my entire life was gone. Being alive minus the answers to the problems you have sorted out all through your good short article is a crucial case, as well as the ones which could have in a negative way affected my entire career if I hadn't discovered your web page. Your own personal capability and kindness in touching all areas was very useful. I don't know what I would've done if I hadn't encountered such a step like this. I can now look ahead to my future. Thanks a lot so much for the high quality and sensible guide. I won't be reluctant to refer your blog to anybody who should receive counselling about this subject matter.

  • jordan 1 off white said

    I must express thanks to this writer just for bailing me out of this scenario. As a result of searching through the internet and getting recommendations which were not powerful, I was thinking my life was well over. Existing minus the approaches to the difficulties you've sorted out through this article is a critical case, and those that would have in a wrong way affected my entire career if I had not noticed the blog. Your good capability and kindness in dealing with every item was priceless. I'm not sure what I would've done if I hadn't encountered such a step like this. I'm able to at this moment look forward to my future. Thanks very much for your impressive and results-oriented guide. I won't hesitate to recommend the website to anybody who needs care on this problem.

  • calvin klein outlet online said

    I am also writing to make you be aware of of the wonderful encounter my wife's daughter gained reading through your web page. She came to find plenty of pieces, which included what it is like to possess a wonderful teaching character to have the mediocre ones easily grasp a number of complicated things. You truly did more than people's expectations. I appreciate you for offering such priceless, dependable, informative not to mention easy tips about the topic to Ethel.

  • kate spade outlet said

    My husband and i got really more than happy Emmanuel could round up his inquiry with the precious recommendations he discovered from your own web site. It is now and again perplexing to simply always be releasing points which often some others have been selling. And we also fully understand we have got the writer to appreciate because of that. The specific explanations you made, the easy site menu, the friendships you will make it easier to promote - it's mostly superb, and it's really helping our son in addition to our family recognize that that idea is cool, and that's really important. Thank you for all the pieces!

  • yeezy boost 350 v2 said

    I wanted to post you a very little word to help say thank you again for those great tricks you have documented on this site. This has been quite pretty open-handed with people like you to deliver without restraint all a lot of people could possibly have sold as an e-book to make some cash on their own, especially given that you could possibly have tried it in the event you desired. Those good ideas also served as a easy way to understand that some people have a similar keenness just like mine to know the truth very much more related to this problem. I am sure there are millions of more enjoyable situations ahead for individuals who read through your blog.

  • coach outlet said

    I have to express my admiration for your generosity in support of men who need help on this study. Your special dedication to getting the message around had become extraordinarily practical and have continually encouraged those like me to realize their ambitions. Your amazing warm and helpful useful information means much a person like me and a whole lot more to my mates. Thanks a lot; from each one of us.

  • retro jordans said

    Thank you for all of the hard work on this site. My aunt really loves carrying out investigation and it is easy to see why. Almost all know all about the compelling method you provide informative items through your blog and welcome participation from other people on this area of interest then my girl has been discovering a lot. Enjoy the remaining portion of the year. You are always carrying out a powerful job.

  • nike air max shoes said

    I have to show some thanks to this writer for rescuing me from such a setting. As a result of surfing around through the internet and coming across concepts which were not pleasant, I believed my entire life was over. Existing minus the approaches to the problems you have fixed all through your article is a critical case, as well as the ones which could have adversely damaged my entire career if I had not discovered your web blog. Your training and kindness in playing with every aspect was important. I'm not sure what I would have done if I hadn't come across such a point like this. I am able to at this time look ahead to my future. Thanks a lot very much for this high quality and amazing guide. I won't be reluctant to endorse your web site to anyone who should get support on this topic.

  • michael kors handbags sale said

    I definitely wanted to develop a quick remark to be able to say thanks to you for some of the great tips and hints you are giving on this site. My time consuming internet search has at the end of the day been rewarded with good suggestions to exchange with my visitors. I 'd tell you that many of us site visitors actually are really blessed to exist in a notable place with so many marvellous professionals with helpful basics. I feel somewhat privileged to have discovered your entire web page and look forward to some more cool minutes reading here. Thanks a lot once more for everything.

  • ultra boost said

    I wish to show some appreciation to the writer for rescuing me from such a condition. Because of exploring throughout the the net and obtaining ideas that were not beneficial, I believed my life was done. Existing devoid of the solutions to the problems you've fixed as a result of the report is a crucial case, and ones that might have in a negative way damaged my career if I hadn't encountered the website. Your main understanding and kindness in touching every item was precious. I'm not sure what I would've done if I had not come upon such a point like this. I am able to now relish my future. Thanks so much for this skilled and result oriented help. I won't hesitate to recommend your blog post to anybody who wants and needs direction on this subject matter.

  • timberland outlet said

    I must show thanks to this writer for bailing me out of this type of challenge. Just after researching through the internet and getting things that were not powerful, I figured my life was well over. Existing minus the solutions to the difficulties you have sorted out all through this website is a crucial case, and the ones which may have in a negative way damaged my career if I had not encountered your site. Your good ability and kindness in playing with everything was excellent. I'm not sure what I would've done if I hadn't come across such a solution like this. I can now relish my future. Thanks for your time so much for your high quality and results-oriented guide. I will not hesitate to refer your web page to any individual who needs and wants guide about this subject.

  • air max 2018 said

    My husband and i felt quite contented Louis could carry out his investigation by way of the precious recommendations he acquired from your very own weblog. It is now and again perplexing just to choose to be giving away guidelines which often other folks might have been trying to sell. And we keep in mind we have got the blog owner to be grateful to for this. The type of explanations you made, the easy blog menu, the relationships you will help to promote - it's most powerful, and it is helping our son in addition to us do think that idea is thrilling, which is certainly pretty serious. Thank you for the whole lot!

  • custom baseball jerseys said

    Thank you so much for providing individuals with an exceptionally spectacular opportunity to discover important secrets from here. It's usually so useful and as well , full of a good time for me and my office mates to visit your site at the least 3 times weekly to read through the latest issues you have. And of course, I'm always pleased with the attractive creative concepts served by you. Some two tips on this page are definitely the best I have ever had.

  • nike shox said

    I抎 need to check with you here. Which isn't something I often do! I take pleasure in studying a publish that may make individuals think. Additionally, thanks for allowing me to comment!

  • nike air max 2017 said

    Youre so cool! I dont suppose Ive read something like this before. So good to search out anyone with some unique ideas on this subject. realy thanks for starting this up. this website is something that is wanted on the internet, someone with somewhat originality. useful job for bringing one thing new to the web!

  • nike huarache said

    There's noticeably a bundle to learn about this. I assume you made sure nice factors in options also.

  • cheap jordans said

    There are certainly loads of details like that to take into consideration. That could be a nice point to bring up. I provide the thoughts above as common inspiration however clearly there are questions just like the one you deliver up where the most important factor will probably be working in sincere good faith. I don?t know if best practices have emerged around issues like that, however I'm sure that your job is clearly identified as a fair game. Both boys and girls really feel the impact of only a second抯 pleasure, for the remainder of their lives.

  • yeezy boost 350 said

    I must express some thanks to the writer just for bailing me out of such a predicament. Just after checking through the world-wide-web and getting ways which were not productive, I was thinking my entire life was well over. Existing without the solutions to the difficulties you have fixed through your main website is a crucial case, and the kind that might have adversely affected my entire career if I hadn't come across your blog. Your good know-how and kindness in dealing with all the stuff was excellent. I'm not sure what I would have done if I had not come across such a solution like this. I can also at this time look ahead to my future. Thank you very much for your impressive and results-oriented help. I won't hesitate to refer your blog post to anybody who ought to have direction on this matter.

  • nike air max shoes said

    I used to be very pleased to search out this internet-site.I wished to thanks in your time for this wonderful learn!! I positively enjoying every little little bit of it and I've you bookmarked to check out new stuff you weblog post.

  • curry shoes said

    My husband and i have been really delighted when Peter could round up his researching while using the precious recommendations he was given through the blog. It is now and again perplexing to simply be handing out things that many many others may have been selling. And we all recognize we now have the blog owner to thank for this. Most of the illustrations you've made, the simple blog menu, the relationships your site make it possible to create - it is everything remarkable, and it's facilitating our son and our family know that the subject matter is amusing, which is highly fundamental. Thank you for the whole thing!

  • jordan 13 said

    You made some respectable factors there. I appeared on the web for the problem and found most individuals will associate with along with your website.

  • nike air max shoes said

    Spot on with this write-up, I actually assume this web site wants far more consideration. I抣l most likely be again to learn far more, thanks for that info.

  • michael jordan shoes said

    There are definitely a whole lot of particulars like that to take into consideration. That is a nice level to convey up. I offer the thoughts above as general inspiration but clearly there are questions just like the one you deliver up the place crucial thing might be working in sincere good faith. I don?t know if greatest practices have emerged round things like that, but I'm sure that your job is clearly recognized as a fair game. Both boys and girls really feel the impact of only a second抯 pleasure, for the remainder of their lives.

  • yeezy boost 350 v2 said

    I must express thanks to this writer for bailing me out of this particular circumstance. Just after scouting throughout the internet and getting notions that were not powerful, I thought my entire life was well over. Living devoid of the approaches to the problems you have fixed through your short post is a serious case, as well as the kind that would have negatively damaged my career if I had not come across your blog. Your actual competence and kindness in handling every item was invaluable. I'm not sure what I would have done if I had not discovered such a thing like this. I'm able to at this time relish my future. Thanks very much for your impressive and effective help. I will not think twice to propose your blog post to any person who requires guide about this situation.

  • yeezy shoes said

    I must express thanks to this writer for bailing me out of such a problem. After checking through the online world and finding advice which were not powerful, I figured my entire life was over. Being alive without the solutions to the issues you have fixed by way of your entire blog post is a critical case, and the kind which could have in a negative way affected my entire career if I had not noticed your web site. Your own personal natural talent and kindness in maneuvering all the details was useful. I don't know what I would have done if I hadn't come across such a subject like this. I'm able to at this moment look forward to my future. Thanks a lot so much for this specialized and sensible guide. I won't think twice to suggest the website to anyone who needs and wants guidelines about this issue.

  • yeezy boost 700 said

    I simply needed to say thanks once again. I'm not certain the things that I would've taken care of in the absence of the actual methods provided by you over this theme. It was actually an absolute distressing issue in my opinion, but encountering a skilled manner you processed that took me to jump for joy. Now i am happy for the advice and then sincerely hope you find out what a powerful job you have been undertaking educating the others by way of a web site. I am sure you have never met all of us.

  • yeezy boost 350 said

    I wish to express some appreciation to the writer just for bailing me out of such a problem. Just after checking throughout the internet and obtaining strategies which were not helpful, I assumed my life was over. Living without the presence of answers to the issues you have fixed all through your short post is a serious case, and ones which could have negatively damaged my career if I hadn't discovered your site. Your main knowledge and kindness in playing with a lot of things was important. I am not sure what I would have done if I had not discovered such a thing like this. I can also at this point relish my future. Thanks for your time very much for the specialized and results-oriented help. I will not think twice to endorse the blog to anyone who should have tips about this situation.

  • hermes belts said

    I have to convey my admiration for your kind-heartedness supporting folks who have the need for help with that subject. Your personal commitment to getting the message all over came to be especially beneficial and have really empowered individuals much like me to get to their goals. Your entire invaluable help and advice implies so much a person like me and further more to my peers. Thanks a ton; from each one of us.

  • zx flux said

    I precisely had to thank you very much once again. I'm not certain the things I could possibly have achieved without the entire thoughts documented by you directly on this field. This has been an absolute frightful problem in my circumstances, but considering a specialized approach you treated the issue forced me to weep over happiness. I am happier for your guidance and believe you know what an amazing job you are always getting into training the mediocre ones through your web blog. Most probably you haven't encountered all of us.

  • 457F3C47-96BA-479F-926C-9F292B9DB1DA said

    I precisely needed to thank you very much yet again. I'm not certain what I could possibly have carried out in the absence of the type of techniques shown by you about such a problem. Certainly was an absolute challenging case in my opinion, but understanding the very professional style you handled that took me to jump for fulfillment. I will be grateful for this help and in addition pray you comprehend what a great job your are getting into educating men and women through the use of your webblog. I'm certain you haven't met any of us.

Add a Comment