當前位置:才華齋>範例>工作總結>

往執行緒裡傳遞引數的方法小結

工作總結 閱讀(2.82W)

傳參方式有兩種:

往執行緒裡傳遞引數的方法小結

1、建立帶參構造方法類 傳參

2、利用t(8)直接傳參,該方法會接收一個物件,並將該物件傳遞給執行緒,因此線上程中啟動的方法

必須接收object型別的單個引數。

Thread (ParameterizedThreadStart) 初始化 Thread 類的新例項,指定允許物件線上程啟動時傳遞給執行緒的委託

Thread (ThreadStart) 初始化 Thread 類的新例項。

由 Compact Framework 支援。

Thread (ParameterizedThreadStart, Int32) 初始化 Thread 類的新例項,指定允許物件線上程啟動時傳遞給執行緒的委託,並指定執行緒的最大堆疊大小。

Thread (ThreadStart, Int32) 初始化 Thread 類的新例項,指定執行緒的最大堆疊大小。

由 Compact Framework 支援。

我們如果定義不帶引數的執行緒,可以用ThreadStart,帶一個引數的用ParameterizedThreadStart。帶多個引數的用另外的方法,下面逐一講述。

一、不帶引數的

using System; using ric; using ; using ading; namespace AAAAAA { class AAA { public static void Main() { Thread t = new Thread(new ThreadStart(A)); t(); (); } private static void A() { eLine("Method A!"); } } }

結果顯示Method A!

二、帶一個引數的

由於ParameterizedThreadStart要求引數型別必須為object,所以定義的方法B形參型別必須為object。

using System; using ric; using ; using ading; namespace AAAAAA { class AAA { public static void Main() { Thread t = new Thread(new ParameterizedThreadStart(B)); t("B"); (); } private static void B(object obj) { eLine("Method {0}!",ring ()); } } }

結果顯示Method B!

三、帶多個引數的

由於Thread預設只提供了這兩種建構函式,如果需要傳遞多個引數,我們可以自己將引數作為類的.屬性。定義類的物件時候例項化這個屬性,然後進行操作。

using System; using ric; using ; using ading; namespace AAAAAA { class AAA { public static void Main() { My m = new My(); m.x = 2; m.y = 3; Thread t = new Thread(new ThreadStart(m.C)); t(); (); } } class My { public int x, y; public void C() { eLine("x={0},y={1}", this.x, this.y); } } }

結果顯示x=2,y=3

四、利用結構體給引數傳值。

定義公用的public struct,裡面可以定義自己需要的引數,然後在需要新增執行緒的時候,可以定義結構體的例項。

//結構體 struct RowCol { public int row; public int col; }; //定義方法 public void Output(Object rc) { RowCol rowCol = (RowCol)rc; for (int i = 0; i < ; i++) { for (int j = 0; j < ; j++) e("{0} ", _char); e("n"); } }