神秘的负反价值 [英] Mysterious Negative Counter Value
问题描述
我正在为项目的每个sql调用创建新线程。有数百万个sql调用,因此我在新线程中调用一个过程来处理sql调用。
这样做,我想增加和减少一个计数器这样我就知道这些线程何时完成了sql查询。
令我惊讶的是,输出在计数器中显示的是负值。怎么样?当我从0开始并在过程开始时加1并在过程结束时减去1时?
在程序中的其他任何地方都没有调用此int ..以下是代码。
public static int counter = 0;
while(!txtstream.EndOfStream)
{
new Thread(delegate()
{
processline();
})。开始();
Console.WriteLine(counter);
}
public static void processline()
{
counter ++;
sql.ExecuteNonQuery();
柜台-;
}
输出看起来像这样:
1
21
-2
-2
5
解决方案没什么好奇怪的,您正在使用线程,对吗?
++
和-
运算符不是线程安全的。public static void processline()
{
Interlocked.Increment(ref counter);
sql.ExecuteNonQuery();
Interlocked.Decrement(参考计数器);
}
I'm creating new threads for every sql call for a project. There are millions of sql calls so I'm calling a procedure in a new thread to handle the sql calls.
In doing so, I wanted to increment and decrement a counter so that I know when these threads have completed the sql query.
To my amazement the output shows NEGATIVE values in the counter. HOW? When I am starting with 0 and adding 1 at the beginning of the process and subtracting 1 at the end of the process?
This int is not called anywhere else in the program.. the following is the 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 something like this:
1 21 -2 -2 5
解决方案Nothing mysterious about it, you are using threading, right?
The
++
and--
operator aren't thread safe. Do this.public static void processline() { Interlocked.Increment(ref counter); sql.ExecuteNonQuery(); Interlocked.Decrement(ref counter); }
这篇关于神秘的负反价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!