c# - Mysterious Negative Counter Value -
i'm creating new threads every sql call project. there millions of sql calls i'm calling procedure in new thread handle sql calls.
in doing so, wanted increment , decrement counter know when these threads have completed sql query.
to amazement output shows negative values in counter. how? when starting 0 , adding 1 @ beginning of process , subtracting 1 @ end of process?
this int not called anywhere else in program.. following code..
public static int counter=0; while(!txtstream.endofstream) { new thread(delegate() { processline(); }).start(); console.writeline(counter); } public static void processline() { counter++; sql.executenonquery(); counter--; }
output looks this:
1 21 -2 -2 5
nothing mysterious it, using threading, right?
the ++
, --
operator aren't thread safe. this.
public static void processline() { interlocked.increment(ref counter); sql.executenonquery(); interlocked.decrement(ref counter); }
Comments
Post a Comment