110,536
社区成员
发帖
与我相关
我的任务
分享
namespace WindowsFormsApplication1 {
public delegate void Notify(int index);
public partial class Form1 : Form {
private Notify NotifyProgress;
public Form1() {
InitializeComponent();
this.NotifyProgress = new Notify(Noti);
}
private void Noti(int index) {
if (this.InvokeRequired) {
// 用当前线程调用委托
this.Invoke(this.NotifyProgress, new object[] { index });
}
else {
// 如果在当前线程则直接赋值,这里就不存在跨线程访问UI的问题了
this.label1.Text = index.ToString();
}
}
private void button1_Click(object sender, EventArgs e) {
Thread thread = new Thread(new ThreadStart(ThreadMethod));
thread.Start();
}
private void ThreadMethod() {
int i = 0;
while (true) {
// 这里模仿你的接受消息的逻辑,我这里等1秒钟
Thread.Sleep(1000);
i++;
// 这里调用委托,我传递一个int,你可以传递一个string出去
this.NotifyProgress(i);
}
}
}
}