子線程訪問主線程控件時,會報出錯。
兩種方法可以實現第一種是,設置線程的檢查方式為無。
第二種是使用委托。第一種沒什么好講的,這里主要講下第二種。
1,首先是委托
delegate
(1)委托的定義:將方法作為方法的參數
(2)定義委托:
delegate void dele(int a, int b);
委托是一種數據類型,就像 int , float,student 學生類一樣
(3)聲明委托變量
dele del1=null;
(4)給委托變量賦值
del=new dele(add); static void add(int a, int b) { Console.WriteLine("加法運算為{0}", a + b); }
(5)調用委托
del(2, 3);
全部代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 委托 { class Program { delegate void dele(int a, int b); static void Main(string[] args) { dele del = null; Console.WriteLine("多播委托,請輸入您要的運算"); Console.WriteLine("+,-,*,/"); string str = Console.ReadLine(); switch (str) { case "+": del = new dele(add); break; case "-": del = new dele(sub); break; case "*": del = new dele(mul); break; case "/": del = new dele(div); break; default: Console.WriteLine("輸入有誤"); break; } weituo(3, 4, del); Console.ReadLine(); } static void weituo(int a,int b,dele del) { del(a, b); } static void add(int a, int b) { Console.WriteLine("加法運算為{0}", a + b); } static void sub(int a, int b) { Console.WriteLine("減法運算為{0}",a-b); } static void mul(int a, int b) { Console.WriteLine("乘法運算為{0}", a*b); } static void div(int a,int b) { Console.WriteLine("除法運算為{0}", a/b); } } }
2 跨線程調用委托
(1)定義類
public class MessageCreate{ }
(2)類中定義委托,定義委托變量,調用委托
public class MessageCreate { //定義委托 public delegate void MyDelegate(ListBox lb, string strMsg); //定義委托變量 public MyDelegate my { get;set; } //調用委托 public void show(ListBox lb, string strMsg){ if (lb.InvokeRequired)//判斷這個控件是否是其他線程調用 lb.BeginInvoke(this.My, new object[] { lb, strMsg }); } }
(3)而給委托變量賦值時要在主線程里面賦值,那么這樣一個異步調用委托就完成了。
//新建一個類 MessageCreate mc = new MessageCreate(); //給類中的委托變量賦值 mc.My = new MessageCreate.MyDelegate(ShowStatus); //調用委托 mc.show() ------------------委托函數-------------------------- public void ShowStatus(ListBox lb, string strMsg) { lock (lb) { if (lb.Items.Count >= 10000) lb.Items.RemoveAt(0); lb.Items.Add(strMsg); lb.Refresh(); } }
大功告成!
