大家知道WPF中多线程访问UI控件时会提示UI线程的数据不能直接被其他线程访问或者修改,该怎样来做呢?

分下面两种情况

1.WinForm程序

 1  
 2 1)第一种方法,使用委托:
 3 private delegate void SetTextCallback(string text);
 4         private void SetText(string text)
 5         {
 6             // InvokeRequired需要比较调用线程ID和创建线程ID
 7             // 如果它们不相同则返回true
 8             if (this.txt_Name.InvokeRequired)
 9             {
10                 SetTextCallback d = new SetTextCallback(SetText);
11                 this.Invoke(d, new object[] { text });
12             }
13             else
14             {
15                 this.txt_Name.Text = text;
16             }
17         }
18 2)第二种方法,使用匿名委托
19         private void SetText(Object obj)
20         {
21             if (this.InvokeRequired)
22             {
23                 this.Invoke(new MethodInvoker(delegate
24                 {
25                     this.txt_Name.Text = obj;
26                 }));
27             }
28             else
29             {
30                 this.txt_Name.Text = obj;
31             }
32         }
33 这里说一下BeginInvoke和Invoke和区别:BeginInvoke会立即返回,Invoke会等执行完后再返回。
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-01
  • 2021-10-12
  • 2021-09-29
  • 2022-12-23
  • 2021-08-02
猜你喜欢
  • 2022-12-23
  • 2021-12-20
  • 2022-12-23
  • 2022-02-27
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案