【发布时间】:2016-06-12 11:47:27
【问题描述】:
使用 System.Threading 的 Win Form 应用程序。两个线程 threadA 和 threadB 使用相同的方法 sumNumber 启动。 sumNumber 更新变量total。所以这两个线程尝试更新同一个变量。
使用监控类同步访问total变量。
在 WindowsFormsApplication2.exe 中出现“类型为 'System.Threading.SynchronizationLockException' 的未处理异常”的运行时异常
附加信息:对象同步方法是从未同步的代码块调用的。
我该如何正确使用这个中的 Monitor 类。
int total;
private void button3_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
total = 0;
Thread threadA;
Thread threadB;
threadA = new Thread(sumNumber);
threadA.Start();
threadB = new Thread(sumNumber);
threadB.Start();
threadA.Join();
threadB.Join();
listBox1.Items.Add("Total is: " + total);
}
public void sumNumber()
{
long numRepeats = 100000;
for (int i = 0; i < numRepeats; i++)
{
Monitor.Enter(total);
total = total + 10;
Monitor.Exit(total);
}
}
【问题讨论】:
标签: c# multithreading winforms