c# 多线程 大家看看为什么 text上面不显示内容
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 yjj
{
public partial class Form1 : Form
{
public int Seed;
public static int m=0;
public Form1()
{
InitializeComponent();
}
private void Form1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, System.EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click_1(object sender, EventArgs e)
{
Form1 v = new Form1();
if (m == 0)
{
v.aa(0);
m++;
}
}
private void button2_Click(object sender, EventArgs e)
{
Class1 v = new Class1();
if (m == 1)
{
v.aa(1);
m = 0;
}
}
public void aa(int ae)
{
//a.textBox1.Text = "a";
// a.textBox2.Text = "b";
Thread a1 = new Thread(new ThreadStart(t1));
Thread a2 = new Thread(new ThreadStart(t2));
if (ae== 0)
{
a1.Start();
a2.Start();
// ae = 0;
}
if (ae == 1)
{
a1.Suspend();
a2.Suspend();
}
}
public void t1()
{
textBox1.Text = "a";
Random N = new Random(Seed);
do
{
textBox1 .Text = N.Next(0, 10).ToString();
Thread.Sleep(100);
}
while (true);*/
}
public void t2()
{
textBox2.Text = "b";
Random N = new Random(Seed);
do
{
textBox2.Text = N.Next(0, 10).ToString();
Thread.Sleep(100);
}
while (true);*/
}
}
}
参考答案:在你给TextBox的Text属性赋值后,紧跟着调用一句
Application.DoEvents();
否则,TextBox的变化基本要等到函数返回后才能看到。上面那个方法强制处理消息队列中的所有消息,不用等到方法返回。
另外,你的代码在编译时应该会有警告的吧?在其他线程中调用绘制Form线程中的方法会产生警告。建议你最好使用Control的Invoke()方法