跨线程访问UI控件的方法(实验使用的就是这个)

其实往后收集的方法都大同小异

禁止对跨线程访问做检查(不使用)

//在Form1_Load中插入
//允许操作其它线程创建的控件
Control.CheckForIllegalCrossThreadCalls = false;

使用委托方法(验证这个方法可行-UI也不卡)

1
2
3
4
5
6
7
8
9
10
11
//跨线程访问UI控件,更新主线程中dataGridView表格内容
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(delegate
{
//此处可用于更新UI控件内容
}
));


}//跨线程访问UI控件,更新主线程中dataGridView表格内容

C# 优雅的解决 多线程中访问 UI 的问题

优雅的解决 多线程中访问 UI 的问题

  1. 在WinForm 程序中可以在Form的构造函数中. 将 “是否检察跨线程的控件访问” 设为 False. 就解决了. 就可以正常的使用控件了.
      Control.CheckForIllegalCrossThreadCalls = false;
  2. 就是使用控件的Invoke 方法
    比如:
      label1.Invoke(new MethodInvoker(delegate () {this.label1.text = “靠…!”;}));
    使用Lambda 表达示会更优雅一点:
      label1.Inovke(new MethodInvoker( () => this.lable1.text = “哈哈..”));
    这是我常用的. 觉得算得上优雅的方法. 如果还有朋友知道列优雅的方法,请留言告知~~!

2012.11.17 日补充

在使用 线程或是使用异步的方法去改变 DataGridView 控件时.. 如果直接使用第一种方法.直接允许控制跨线程访问的话. 会有这样的问题(很是恼人) :

用delegate的BeginInvoke去更新DataGridView时,当异步调用完成后有这样现象:

  1. 如果更新后DataGridView没有出现滚动条,程序会正常运行
  2. 如果更新后DataVridView出现了滚动条,程序会卡死

解决的方法是 不要使用 第一种方法: 这种方法 虽然方便.. 但会带来一些意料不到的问题. 还是这样来更新控件:

1
label1.Inovke(new MethodInvoker( () => this.lable1.text = "哈哈.."));

这个MethodInvoker只是一个 返回值,无参数的代理而已. 所以你也可能 自己定义一个 比如: public delegate void MyInvoker(); 然后使用

1
label1.Inovke(new MyInvoker( () => this.lable1.text = "哈哈.."));  是一样的.

同样你也可以 使用 Action

1
label1.Inovke(new Action( () => this.lable1.text = "哈哈.."));

而且. 可以通过 Control.InvokeRequired 方法 ,来判断,当前访问这个控件的线程 是否是UI线程.是否需要使用 Invoke方法.

1
2
3
4
5
if (this.dgv.InvokeRequired) {
  this.dgv.Invoke(new MethodInvoker(()=>dgv.DataSource = ds.Tables[0]));
} else { // 如果是 UI 主线程更新的话
  this.dgv.DataSource = ds.Tables[0];
}

关于Invoke的拥有者:Control

因为Control.Invoke含义是将方法委托给 拥有该Control 的线程去执行。因些.我们不需要使用 this.label1.Invoke 或是 this.DataGridView,Invoke 可以直接使用 : this.Invoke. this 指针也就是当前的 UI 主线程.

就好似 A 跟 B 说, 我不方便去你家, 你帮我用你家的电脑下点电影什么的. A 不允许直接使用 B的电脑. 但他可以让B帮他完成一些事情. B得到了 A的一些求助. 自己去使用属于自己的电脑. 这个比喻就充分的表达了.. 两个线程间的交流.

1
2
3
4
5
6
7
8
9
public void Method_A_Thread() {

  // Do something

// 让UI线程帮忙完成些 ,属于 UI线程里的内容

// this.Invoke(new Action(() => this.label.Text = "xxx"));

}

Winform中如何跨线程访问UI元素

在C# 的应用程序开发中, 我们经常要把UI线程和工作线程分开,防止界面停止响应, 同时我们又需要在工作线程中更新UI界面上的控件。但直接访问会出现“线程间操作无效”的情况,因为.NET禁止了跨线程调用控件, 否则谁都可以操作控件,最后可能造成错误。 下面介绍几种跨线程访问的方法:

1、禁止对跨线程访问做检查 (不推荐使用这种方法)

这种方法不检查跨线程访问,允许各个线程操作UI元素,容易出现错误。

1
2
3
4
5
6
public Form2()
{
InitializeComponent();
//禁止对跨线程访问做检查 (不推荐使用这种方法)
Control.CheckForIllegalCrossThreadCalls = false;
}

2、使用委托方法 将其委托给UI控件更新

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//使用委托方法 将其委托给UI控件更新
private void button1_Click(object sender, EventArgs e)
{
Thread thread1 = new Thread(new ParameterizedThreadStart(UpdateLabel2));
thread1.Start("更新Label");
}

private void UpdateLabel2(object str)
{
if (label2.InvokeRequired)
{
// 当一个控件的InvokeRequired属性值为真时,说明有一个创建它以外的线程想访问它
Action<string> actionDelegate = (x) => { this.label2.Text = x.ToString(); };
// 或者
// Action<string> actionDelegate = delegate(string txt) { this.label2.Text = txt; };
this.label2.Invoke(actionDelegate, str);
}
else
{
this.label2.Text = str.ToString();
}
}

3、使用delegate和BeginInvoke来从其他线程中控制控件

只要把上面的 this.label2.Invoke(actionDelegate, str); 中的 Invoke 改为BeginInvoke方法就可以了。

Invoke方法和BeginInvoke方法的区别是:
Invoke方法是同步的, 它会等待工作线程完成,BeginInvoke方法是异步的, 它会另起一个线程去完成工作线。

4、使用同步上下文:SynchronizationContext方法

该方法是取得主线程的上下文信息,然后在子线程将访问UI控件方法推送到UI上下文的消息队列里,使用POST或者Send;

1
2
3
4
5
6
7
8
9
10
11
private SynchronizationContext synchronizationContext;

private void button2_Click(object sender, EventArgs e)
{
synchronizationContext = SynchronizationContext.Current;
new Thread(() => { UpdateText("跨线程访问"); }).Start();
}
void UpdateText(string msg)
{
synchronizationContext.Post(_ => this.label2.Text = msg, null);
}

5、使用BackgroundWorker组件(推荐使用这个方法)

个人感觉没有自己开线程方便,因为还得在窗体上拉控件

BackgroundWorker是.NET里面用来执行多线程任务的控件,它允许编程者在一个单独的线程上执行一些操作。耗时的操作(如下载和数据库事务)。

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
public partial class FileManagerForm : Form
{
FileInfo file ;
BackgroundWorker bw;
ServerFile server;
public FileManagerForm(string filePath)
{
InitializeComponent();

file = new FileInfo(filePath);

long size = file.Length / 1024 / 1024;
lblOrgSize.Text = (int)size+ "MB";
bw = new BackgroundWorker();
server = new ServerFile(file.Name);
}

private void FileManagerForm_Load(object sender, EventArgs e)
{
proUpFile.Minimum = 0;
proUpFile.Maximum = 100;

bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += Bw_DoWork;
bw.ProgressChanged += Bw_ProgressChanged;
bw.RunWorkerCompleted += Bw_RunWorkerCompleted;
bw.RunWorkerAsync();
}
private void Bw_DoWork(object sender, DoWorkEventArgs e)
{
using(FileStream fileRead= file.OpenRead())
{
long setp = file.Length / 100;
while (file.Length > fileRead.Position)
{
if (bw.CancellationPending)
{
break;
}

byte[] bytes = new byte[1024];
int count = fileRead.Read(bytes, 0, bytes.Length);

long writeLength= server.UpFile(bytes, count);

if(writeLength >proUpFile.Value* setp)
{
int size = (int)(writeLength / 1024 / 1024);
bw.ReportProgress(proUpFile.Value + 1, size);
}

}
server.Close();
}
}
private void Bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
proUpFile.Value= e.ProgressPercentage> proUpFile.Maximum?proUpFile.Maximum:e.ProgressPercentage;
lblUpLoadSize.Text = e.UserState.ToString() + "MB";
}

private void Bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (this.proUpFile.Value == this.proUpFile.Maximum)
{
MessageBox.Show("文件发送成功!");
}
else
{
MessageBox.Show("文件发送失败!");
}
this.Close();
}

private void btnCancel_Click(object sender, EventArgs e)
{
bw.CancelAsync();
}
}

相关链接(侵删)

  1. C#跨线程访问UI控件的方法
  2. C# 优雅的解决 多线程中访问 UI 的问题
  3. Winform中如何跨线程访问UI元素

=================我是分割线=================

欢迎到公众号来唠嗑: