多线程同时运行问题
我的程序如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace MultiThread
{
public partial class frmMain : Form
{
int a = 0;
int b = 0;
ThreadStart start;
Thread newthread ;
ThreadStart end ;
Thread newthread1;
public frmMain()
{
InitializeComponent();
}
private void btnThread_Click(object sender, EventArgs e)
{
newthread1.Start();
newthread.Start();
}
private void frmMain_Load(object sender, EventArgs e)
{
end = new ThreadStart(UpdateText1);
newthread1 = new Thread(end);
start = new ThreadStart(UpdateText);
newthread = new Thread(start);
}
private void UpdateText1()
{
for (int i = 0; i < 2000; i++)
{
a = i;
eee.Text = a.ToString();
}
}
private void UpdateText()
{
for (int i = 0; i < 2000; i++)
{
b = a;
hhh.Text = b.ToString();
}
}
private void btnAbort1_Click(object sender, EventArgs e)
{
newthread.Abort();
}
}
}
我本想看到hhh.Text与eee.Text一齐变,最后都为1999,但运行时hhh.Text立即变为0,而eee.Text连续的增加变为1999,请高手指点,我在a=i,b=a,后都加入Thread.Sleep(50);时,可以看到我想要的结果。
------解决方案--------------------你把循环调整到200000
再运行看看
------解决方案--------------------对于控件eee,hhh的操作要通过Invoke的方式在UI线程里面操作, 否则程序的行为会产生未知的后果.