Invoke的使用情景

直接看代码:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Windows.Forms;
 9 using System.Threading;
10 
11 namespace Invoke的测试
12 {
13     public partial class Form1 : Form
14     {
15         public Form1()
16         {
17             InitializeComponent();
18         }
19 
20         private void button1_Click(object sender, EventArgs e)
21         {
22             Thread thd = new Thread(new ParameterizedThreadStart(ThreadMethod));
23             thd.IsBackground = true;
24             thd.Start("Changed");
25         }
26 
27         private void ThreadMethod(object arg)
28         {
29             // 判断如果要改变 label1的属性在"此时"是否需要Invoke(这个是动态的,取决于本函数的此次执行是在哪个线程)
30             if (label1.InvokeRequired)  // 因为我要改变的是 label1的属性,故要用 label1.InvokeRequired
31             {
32                 // 这一句 label1.Invoke(func); 是指在label1所在的线程(创建lable1的线程)里调用 func(func排在label1所在线程正在执行的任务后面其它任务的前面)
33                 // 比如 Main中执行 int a+b; b=3; Main函数所在线程执行时是将这两句代码分为两个任务(笼统的),正在执行 int a+b;时,调用了 Invoke,则将func
34                 // 放在b=3; 之前执行。
35                 // 故label1可以替换this / button1 / label1,但是最好是要改变哪个控件属性值就用该控件的 Invoke
           // 这里写的不好,可以直接label1.Invoke(ThreadMethod....);而不用再声明一个方法InvokeMethod 36 label1.Invoke(new Action(InvokeMethod)); 37 } 38 else 39 label1.Text = arg.ToString(); 40 } 41 42 private void InvokeMethod() 43 { 44 label1.Text = "Changed"; 45 } 46 } 47 }

说明都在注释里了。

原文地址:https://www.cnblogs.com/silentdoer/p/4997753.html