在窗体设计中,会经常遇到跨线程访问窗体控件,如果直接访问会报错,那怎么办呢?直接上代码
代码为一个类,实际运用的时候直接实例化调用即可
1 class CrossThreadUpdateUIClass 2 { 3 4 public void ChangeBtnTxt(Button Btn, string Str) 5 { 6 Action<Button, string> DoAction = delegate (Button btn, string str) 7 { 8 9 if (btn.InvokeRequired) 10 { 11 btn.Text = str; 12 //btn.BackColor = ; ; ; 13 } 14 else 15 { 16 btn.Text = str; 17 } 18 }; 19 Btn.Invoke(DoAction, Btn, Str); 20 21 22 } 23 public void ChangeLabelTxt(Label Lb, string Str) 24 { 25 26 Action<Label, string> DoAction = delegate (Label lb, string str) 27 { 28 29 30 if (lb.InvokeRequired) 31 { 32 lb.Text = str; 33 //btn.BackColor = ; ; ; 34 } 35 else 36 { 37 lb.Text = str; 38 39 } 40 41 }; 42 43 Lb.Invoke(DoAction, Lb, Str); 44 45 } 46 public void ChangeControllTxt(Control Ctl, string Str) 47 { 48 Action<Control, string> DoAction = delegate (Control ctl, string str) 49 { 50 51 52 if (ctl.InvokeRequired) 53 { 54 ctl.Text = str; 55 //btn.BackColor = ; ; ; 56 } 57 else 58 { 59 ctl.Text = str; 60 61 } 62 63 }; 64 65 Ctl.Invoke(DoAction, Ctl, Str); 66 67 } 68 public void ChangeUserLabelValue(UserLabel userlabel, string text) 69 { 70 Action<UserLabel, string> DoAction = delegate (UserLabel usl, string str) 71 { 72 73 74 if (usl.InvokeRequired) 75 { 76 usl.Text = str; 77 if(str=="PASS") 78 { 79 usl.BackColor = Color.Green; 80 } 81 else if(str == "FAIL") 82 { 83 usl.BackColor = Color.Red; 84 } 85 } 86 else 87 { 88 usl.Text = str; 89 if (str == "PASS") 90 { 91 usl.BackColor = Color.Green; 92 } 93 else if (str == "FAIL") 94 { 95 usl.BackColor = Color.Red; 96 } 97 } 98 99 }; 100 101 userlabel.Invoke(DoAction, userlabel, text); 102 103 } 104 105 public void UpdateControlAsync(Action act) 106 { 107 Task task = new Task(act); 108 109 task.Start(); 110 } 111 }
标签:控件,string,C#,Text,usl,DoAction,线程,str,btn From: https://www.cnblogs.com/HomeSapiens/p/16859780.html