[我使用线程池创建了一个简单的应用程序,但是当我在线程池内部或外部进行计数器操作时,它在所有情况下都只返回零,还是在非序号处返回?
我的程序[我正在发送1万个有价值的webrequest [API],我知道线程池更快吗?因为我想在5到10分钟内发送和接收10,000个请求。 ]
public int Count;
private void TaskCallBack(Object ThreadNumber)
{
MessageBox.Show(Count.ToString());
Interlocked.Increment(ref Count);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
//// Queue the task.
for (int x = 0; x < 10; x++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(TaskCallBack));
}
this.Count = 0;
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex);
}
}
将this.Count的分配从for语句的下面移到上面。
try
{
this.Count = 0; // <- move this here
//// Queue the task.
for (int x = 0; x < 10; x++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(TaskCallBack));
}
}