Thread (ParameterizedThreadStart) 初始化 Thread 類的新實例,指定允許對象在線程啓動時傳遞給線程的委託。
Thread (ThreadStart) 初始化 Thread 類的新實例。
由 .NET Compact Framework 支持。
Thread (ParameterizedThreadStart, Int32) 初始化 Thread 類的新實例,指定允許對象在線程啓動時傳遞給線程的委託,並指定線程的最大堆棧大小。
Thread (ThreadStart, Int32) 初始化 Thread 類的新實例,指定線程的最大堆棧大小。
由 .NET Compact Framework 支持。
我們如果定義不帶參數的線程,可以用ThreadStart,帶一個參數的用ParameterizedThreadStart。帶多個參數的用另外的方法,下面逐一講述。
一、不帶參數的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
using
System; using
System.Collections.Generic; using
System.Text; using
System.Threading; namespace
AAAAAA { class
AAA {
public
static void
Main() {
Thread t =
new Thread( new
ThreadStart(A)); t.Start();
Console.Read();
}
private
static void
A() {
Console.WriteLine( "Method A!" );
}
}
} |
結果顯示Method A!
二、帶一個參數的
由於ParameterizedThreadStart要求參數類型必須爲object,所以定義的方法B形參類型必須爲object。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
using
System; using
System.Collections.Generic; using
System.Text; using
System.Threading; namespace
AAAAAA { class
AAA {
public
static void
Main() {
Thread t =
new Thread( new
ParameterizedThreadStart(B)); t.Start( "B" );
Console.Read();
}
private
static void
B( object
obj) {
Console.WriteLine( "Method {0}!" ,obj.ToString ());
}
}
} |
結果顯示Method B!
三、帶多個參數的
由於Thread默認只提供了這兩種構造函數,如果需要傳遞多個參數,我們可以自己將參數作爲類的屬性。定義類的對象時候實例化這個屬性,然後進行操作。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
using
System; using
System.Collections.Generic; using
System.Text; using
System.Threading; 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.Start();
Console.Read();
}
}
class
My {
public
int x, y;
public
void C()
{
Console.WriteLine( "x={0},y={1}" ,
this .x,
this .y);
}
}
} |
結果顯示x=2,y=3
四、利用結構體給參數傳值。
定義公用的public struct,裏面可以定義自己需要的參數,然後在需要添加線程的時候,可以定義結構體的實例。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
//結構體
struct
RowCol {
public
int row;
public
int col;
};
//定義方法
public
void Output(Object rc) {
RowCol rowCol = (RowCol)rc;
for
( int
i = 0; i < rowCol.row; i++) {
for
( int
j = 0; j < rowCol.col; j++) Console.Write( "{0} " , _char);
Console.Write( "\n" );
}
} |