C#跨线程访问控件

跨线程访问控件,主要用到控件的属性判断InvokeRequired是否为true,为true则为其他线程创建。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using System;
using System.Windows.Forms;
using System.Threading;

namespace 跨线程控件访问
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
StartPosition = FormStartPosition.CenterParent;
}

private void button1_Click(object sender, EventArgs e)
{
Thread thread1 = new Thread(() => {
if (lbl1.InvokeRequired) { //判断是否调动Invoke方法, 如果为 true 则是其他方法创建。
for (int i = 0; i <= 50; i++) {
//Invoke()方法的第一个参数是返回值为void的委托,第二个是给委托对应方法传递的参数
lbl1.Invoke(new Action<string>(s => lbl1.Text = i.ToString()), i.ToString());
Thread.Sleep(50);
}
}
});
thread1.IsBackground = true;
thread1.Start();
}

private void button2_Click(object sender, EventArgs e)
{
Thread thread2 = new Thread(() => {
if (lbl2.InvokeRequired) { //判断是否调动Invoke方法, 如果为 true 则是其他方法创建。
for (int i = 0; i <= 50; i++) {
//Invoke()方法的第一个参数是返回值为void的委托,第二个是给委托对应方法传递的参数
lbl1.Invoke(new Action<string>(s => lbl2.Text = i.ToString()), i.ToString());
Thread.Sleep(50);
}
}
});
thread2.IsBackground = true;
thread2.Start();
}
}
}

输出:

运行效果

感谢支持!