【3】多线程的重入和并发
Form1的构造方法是忽略检查UI线程跨略的功能,因为默认只有UI线程,也就是系统默认的线程才能对UI进行操作,否则就会报错。
这是这段代码的最终结果,但是理论上应该是10000,为什么会是这个数字呢,
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}
private void button3_Click(object sender, EventArgs e)
{
var thread = new Thread(Test2);
thread.IsBackground = true;
thread.Start();
var thread1 = new Thread(Test2);
thread1.IsBackground = true;
thread1.Start();
}
private void Test2()
{
for (var j = 0; j < 5000; j++)
{
var i = int.Parse(txtSum.Text);
i++;
txtSum.Text = i.ToString();
}
}
就是因为并发了,2个线程在同时执行这段代码。那么解决的方法就是把这个线程的代码加锁。
private void button3_Click(object sender, EventArgs e)
{
var thread = new Thread(Test2);
thread.IsBackground = true;
thread.Start();
var thread1 = new Thread(Test2);
thread1.IsBackground = true;
thread1.Start();
}
private void Test2()
{
lock (this)
{
for (var j = 0; j < 5000; j++)
{
var i = int.Parse(txtSum.Text);
i++;
txtSum.Text = i.ToString();
}
}
}
这样就解决了。