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 线程UI界面响应测试
{
public partial class Form1 : Form
{
delegate void t();
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(ok));
t.Start();
}
public void ok()
{
if (textBox2.InvokeRequired)//为了保证线程的安全性
{
MessageBox.Show("as");
t tt = new t(a);
textBox2.Invoke(tt);
}
else
a();
}
public void a()
{
for (int i = 0; i <= 1000; i++)
textBox2.Text += i;
}
}
}
这是我的程序,通过数数字来测试的我,我想达到的效果是textBox2记录数数字的结果,因为它是我单独开的线程,所以我就想这样子也许能解决数数字照样数,不会等到数完之后界面才能响应下一步的,因为是使用了异步委托,但是结果不是如果所料,在程序运行期间,如果我点击winform框上的其它textbox想进行填写一些其它数据的话,是不行的,会出现未响应的状态,知道那个数数字的程序执行完之后才能再其它的textbox进行输入操作!如何解决??
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;namespace 线程UI界面响应测试
{
public partial class Form1 : Form
{
delegate void t();
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(ok));
t.Start();
}
public void ok()
{
if (textBox2.InvokeRequired)//为了保证线程的安全性
{
MessageBox.Show("as");
t tt = new t(a);
textBox2.Invoke(tt);
}
else
a();
}
public void a()
{
for (int i = 0; i <= 1000; i++)
textBox2.Text += i;
}
}
}
这是我的程序,通过数数字来测试的我,我想达到的效果是textBox2记录数数字的结果,因为它是我单独开的线程,所以我就想这样子也许能解决数数字照样数,不会等到数完之后界面才能响应下一步的,因为是使用了异步委托,但是结果不是如果所料,在程序运行期间,如果我点击winform框上的其它textbox想进行填写一些其它数据的话,是不行的,会出现未响应的状态,知道那个数数字的程序执行完之后才能再其它的textbox进行输入操作!如何解决??
能不能不要这句
textBox2.Invoke(tt);这样做你的多线程毫无意义...
public void ok()
{
test t = delegate(int tmp) { this.textBox2.Text += tmp; this.textBox2.Refresh(); };
for (int i = 0; i <= 1000; i++)
this.Invoke(t, new int[] { i });
}
private void button6_Click(object sender, EventArgs e)
{
new Thread((ThreadStart)delegate
{
for (int i = 0; i <= 1000; i++)
{
textBox2.Invoke((EventHandler)delegate { textBox2.AppendText(i.ToString()); });
}
}).Start();
}
() =>
{
writer = new StreamWriter(pipe);
Marshaller.PreProcess(ident, feedReader, writer);
writer.Flush();
writer.Dispose();
}
)
{
Name = ident.VendorCode + ident.FileCode + "PipeWriterThread",
}.Start();
他的答案基本上是对的,指出了楼主的主要毛病。
把for计数循环写在ui更新线程里,自然会卡。但是上边的答案中,也不能完全的解决卡界面的问题。需要在for循环中加一个Thread.Sleep(),这样ui线程才有空闲时间去响应来自界面上的用户事件。