神秘的负计数器值

Jos*_*ith 0 c# sql counter

我正在为项目的每个 sql 调用创建新线程。有数百万个 sql 调用,因此我在新线程中调用一个过程来处理 sql 调用。

在此过程中,我想增加和减少一个计数器,以便我知道这些线程何时完成 SQL 查询。

令我惊讶的是,计数器的输出显示负值。如何?当我从 0 开始并在过程开始时加 1 并在过程结束时减 1 时?

这个 int 没有在程序的其他地方被调用。以下是代码。

public static int counter=0;

while(!txtstream.EndOfStream)
{
    new Thread(delegate()
    {
        processline();
    }).Start();
    Console.WriteLine(counter);
}

public static void processline()
{
    counter++;
    sql.ExecuteNonQuery();
    counter--;
}
Run Code Online (Sandbox Code Playgroud)

输出看起来像这样:

1
21
-2
-2
5
Run Code Online (Sandbox Code Playgroud)

Aro*_*ron 5

这没什么神秘的,你正在使用线程,对吧?

and++运算--符不是线程安全的。做这个。

public static void processline()
{
    Interlocked.Increment(ref counter);
    sql.ExecuteNonQuery();
    Interlocked.Decrement(ref counter);
}
Run Code Online (Sandbox Code Playgroud)