DonAithnen (donaithnen) wrote,

  • Mood:

Ugly code

Well i found one of the problems with the code i'm working on, though unfortunately not the big nasty ones i'm still dealing with from yesterday.

Once i hacked my way around the XML/Enterprise stuff everything seemed to be working fine, except occasionally the initialization of the static security mapping would throw an error saying it tried to add a duplicate value to the list. The code in the second was something like (in abbreviated form obviously):

if (mapping.Count == 0)
{lock (mapping)
{add stuff to mapping}}

I double checked by adding another static variable in the inner loop to keep track of how often it got initialized, and sure enough it was managing to get inside that code block twice. When i checked "lock" on MSDN it turns out that if something else tries to lock the object it just blocks and waits until the object is unlocked, then continues on its merry way. So in this particular case it doesn't prevent a collision, it just delays it.

so i can either move the mapping.Count check inside the lock, so only one thread can be checking it at a time, or just copy/paste the same check inside the lock loop as well. MSDN doesn't say, but i presume a lock action is more computationally intensive then just checking the Count, and since 99% of the time the first check is enough to prevent the collision without resorting to getting a lock it would make more sense from that perspective to check it twice, both before and after the lock. However repeating the .Count check twice like that just _looks_ dumb. Maybe i can find a variant of lock that skips instead of blocks?

And no, i didn't write this code originally, i'm just supposed to be moving it from the Enterprise project to the local project. I'm not sure why it (presumably) worked in the old location without the same error, and i'm kinda reluctant to change the code too much, like trying to rewrite it so the initialization happens somewhere else so i'm sure it can only get called once. Especially not when i'm still obviously unfamiliar with most of the details of C# =P
Tags: programming

  • Hugo Award Semifinals

    Edit: I wrote this yesterday, not realizing that the finalists would be announced today. My speculations about who's likely to get nominated are…

  • It's alive!

    *tap tap tap* Is this thing on? So for those who don't follow me on twitter, yes i still exist! (For those who do follow me on twitter, sorry for…

  • Why You Should Vote

    This CGP Grey video on the politics of power addresses it partway through (about 7:00 - 8:00). This Cracked…

  • Post a new comment


    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.