XNA Creators Club Online
Page 1 of 1 (3 items)
Sort Posts: Previous Next

Threads. Weird problem

Last post 5/15/2008 7:55 PM by ArenAzul. 2 replies.
  • 5/15/2008 5:15 PM

    Threads. Weird problem

    I'll explain.

    I have a static method where i add an item to a collection, then i run a foreach over that collection and finally, after that foreach, i remove one item from the collection. The problem is the following one:

    When i run only the thread that uses that static method, there's no problem at all.

    But when i launch other threads that are not using that static method (about this i'm very sure) or even when i just use a messagebox anywhere in my code, it happens sometimes that an exception jumps in that method, or another times, it duplicates or triplicates randomly the effect of that method. The exception is the one that it would apear if i run that static method in paralel mode and with different speeds, so sometimes the collection is modified inside the foreach, or sometimes it arrives that one of the items of the collection is null when an operation over it is tried. I'm pretty sure that i don't modify the collection inside the foreach, because i've tried just leaving cleared the code inside the foreach or even just doing an integer addition operation.

    I've also tried with a mutex waitone just at the static method start and a release just before its end, but same problem, so i guess it happens something like "one thread random duplication", because that's the only explanation i find to make the mutex fail. It's actually the same thread using that method twice or three or four times at the same time :D.

    Someone has any idea? Do i have any misunderstanding?

     

    Thanks in advance.

  • 5/15/2008 5:26 PM In reply to

    Re: Threads. Weird problem

    try locking the collection before adding to it.

    lock(mycollection)
    {
    mycollection.Add(value);
    }

    Joel Martinez - XNA MVP
    Blog: http://codecube.net
    Play Videos on an XNA Texture: Scurvy Media
    XNA Unit Testing: Scurvy Test
  • 5/15/2008 7:55 PM In reply to

    Re: Threads. Weird problem

    Yep sorry... i forgot to say i already did that. I even tried to make a very rudimentary tool with a bool and a while() but same thing again.
Page 1 of 1 (3 items) Previous Next