C#线程,能不能每个线程都能控制控件输出呀
代码
public Form1()
{
InitializeComponent();
}
public delegate void dd();
private void f()
{
while (true)
{
Thread.Sleep(1000);
Print();
}
}
public void Print()
{
if (this.textBox1.InvokeRequired)//检查当前线程是不是控件所在线程
{
dd g = new dd(Print);
this.Invoke(g);
}
else
{
if (Thread.CurrentThread.Name == "1")
{
textBox1.Text += "1";
}
else if (Thread.CurrentThread.Name == "2")
{ textBox1.Text = "2"; }
else
{ textBox1.Text += "f"; }
}
}
private void Form1_Load(object sender, EventArgs e)
{
Thread t1 = new Thread(new ThreadStart(f));
//ThreadStart t = new ThreadStart(f);
//Thread t1 = new Thread(t);
t1.Name = "1";
t1.Start();
t1.IsBackground = true;
Thread t2 = new Thread(new ThreadStart(f));
t2.Name = "2";
t2.IsBackground = true;//设置为后台进程
t2.Start();
}
我发现为什么,只会输出ffffffff,难道不能让t1,t2都改变textbox的值吗,这个说到底t1,t2没什么用,求大神改一改,让运行到线程t1时输出1,线程t2时输出2
------解决方案--------------------
看错了。还是稍微有点靠谱的。
但是问题在于,这代码当然只能输出f,因为
if (Thread.CurrentThread.Name == "1")或者
if (Thread.CurrentThread.Name == "2")根本就不可能成立,当当前线程不是主线程的时候
if (this.textBox1.InvokeRequired)肯定是true。