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

  • Minecraft, Might & Magic, and Macros

    Friday when i got home form work i was inspired to try and get my Minecraft server working again. I think it had been lapsed for about a year and a…

  • Stop being stupid Google!

    Fuck you Google Music. I love the idea of buying DRM free music from a source that isn't iTunes or Amazon, but fuck you and your stupid useless UI.…

  • Things that don't work

    I love the Android news widget on my Nexus One. I'm probably much more aware of world events than i have been since i stopped visiting Yahoo News way…

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