【轉載】在C#中主線程和子線程如何實現互相傳遞數據
阿新 • • 發佈:2018-08-25
system generic ack tex href lin threading cti 利用
引用:https://blog.csdn.net/shuaihj/article/details/41316731
一、不帶參數創建Thread
using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace ATest { class A { public static void Main() { Thread t = new Thread(new ThreadStart(A)); t.Start(); Console.Read(); } private static void A() { Console.WriteLine("不帶參數 A!"); } } }
結果顯示“不帶參數 A!”
二、帶一個參數創建Thread
由於ParameterizedThreadStart要求參數類型必須為object,所以定義的方法B形參類型必須為object。
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.Threading; 5 6 namespace BTest 7 { 8 class B 9 { 10 public static void Main()11 { 12 Thread t = new Thread(new ParameterizedThreadStart(B)); 13 t.Start("B"); 14 15 Console.Read(); 16 } 17 18 private static void B(object obj) 19 { 20 Console.WriteLine("帶一個參數 {0}!",obj.ToString ()); 21 } 22 } 23 }
結果顯示“帶一個參數 B!”
三、帶多個參數創建Thread
由於Thread默認只提供了這兩種構造函數,如果需要傳遞多個參數,可以基於第二種方法,將參數作為類的屬性傳給線程。
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.Threading; 5 6 namespace CTest 7 { 8 class C 9 { 10 public static void Main() 11 { 12 MyParam m = new MyParam(); 13 m.x = 6; 14 m.y = 9; 15 16 Thread t = new Thread(new ThreadStart(m.Test)); 17 t.Start(); 18 19 Console.Read(); 20 } 21 } 22 23 class MyParam 24 { 25 public int x, y; 26 27 public void Test() 28 { 29 Console.WriteLine("x={0},y={1}", this.x, this.y); 30 } 31 } 32 }
結果顯示“x=6,y=9”
四、利用回調函數給主線程傳遞參數
我們可以基於方法三,將回調函數作為類的一個方法傳進線程,方便線程回調使用。
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.Threading; 5 6 namespace CTest 7 { 8 class C 9 { 10 public static void Main() 11 { 12 MyParam m = new MyParam(); 13 m.x = 6; 14 m.y = 9; 15 m.callBack = ThreadCallBack; 16 17 Thread t = new Thread(new ThreadStart(m.Test)); 18 t.Start(); 19 20 Console.Read(); 21 } 22 } 23 24 private void ThreadCallBack(string msg) 25 { 26 Console.WriteLine("CallBack:" + msg); 27 } 28 29 private delegate void ThreadCallBackDelegate(string msg); 30 31 class MyParam 32 { 33 public int x, y; 34 public ThreadCallBackDelegate callBack; 35 36 public void Test() 37 { 38 callBack("x=6,y=9"); 39 } 40 } 41 }
結果顯示“CallBack:x=6,y=9”
【轉載】在C#中主線程和子線程如何實現互相傳遞數據