最简单的跨线程调用控件的实例,代码精简,容易理解。一个是带参数的委托,一个是不带参数的委托,代码不同,效果一样。
先来一个不带参数的委托
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private delegate void ThreadWork();
Thread thread;
private void button1_Click(object sender, EventArgs e)
{
//thread = new Thread(new ThreadStart(CrossThreadFlush)); //两种写法不知道有什么区别
thread = new Thread(CrossThreadFlush);
thread.IsBackground = true;
thread.Start();
}
private void CrossThreadFlush()
{
while (true)
{
//将sleep和无限循环放在等待异步的外面
for (int i = 1; i < 100; i++)
{
ThreadFunction();//委托要做的事情
Thread.Sleep(500);
}
}
}
private void ThreadFunction()
{
if (label1.InvokeRequired)//等待异步
{
ThreadWork fc = new ThreadWork(ThreadFunction);
this.Invoke(fc);//通过代理调用刷新方法
// this.Invoke(fc, new object[1] { i });
}
else
{
label1.Text = DateTime.Now.ToString();
label1.Refresh();//不加也没影响
richTextBox1.AppendText(DateTime.Now.ToString()+"\r\n");
}
}
}
}
接下来是带参数的委托
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private delegate void ThreadWork(string contern);
Thread thread;
private void button1_Click(object sender, EventArgs e)
{
//thread = new Thread(new ThreadStart(CrossThreadFlush));
thread = new Thread(CrossThreadFlush);
thread.IsBackground = true;
thread.Start();
}
private void CrossThreadFlush()
{
while (true)
{
//将sleep和无限循环放在等待异步的外面
string time = DateTime.Now.ToString();
for (int i = 1; i < 100; i++)
{
ThreadFunction(time);//委托要做的事情
Thread.Sleep(500);
}
}
}
private void ThreadFunction(string value)
{
if (label1.InvokeRequired)//等待异步
{
ThreadWork fc = new ThreadWork(ThreadFunction);
// this.Invoke(fc);//通过代理调用刷新方法
this.Invoke(fc, new object[1] { value });
}
else
{
label1.Text = DateTime.Now.ToString();
label1.Refresh();//不加也没影响
richTextBox1.AppendText(value+"\r\n");
}
}
}
}