Thread (ParameterizedThreadStart) 初始化 Thread 類的新實例,指定允許對象在線程啟動時傳遞給線程的委托。
Thread (ThreadStart) 初始化 Thread 類的新實例。
由 .NET Compact Framework 支持。
Thread (ParameterizedThreadStart, Int32) 初始化 Thread 類的新實例,指定允許對象在線程啟動時傳遞給線程的委托,並指定線程的最大堆棧大小。
Thread (ThreadStart, Int32) 初始化 Thread 類的新實例,指定線程的最大堆棧大小。
由 .NET Compact Framework 支持。
我們如果定義不帶參數的線程,可以用ThreadStart,帶一個參數的用ParameterizedThreadStart。帶多個參數的用另外的方法,下面逐一講述。
一、不帶參數的
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!
二、帶一個參數的
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默認只提供了這兩種構造函數,如果需要傳遞多個參數,我們可以自己將參數作為類的屬性。定義類的對象時候實例化這個屬性,然后進行操作。
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,里面可以定義自己需要的參數,然后在需要添加線程的時候,可以定義結構體的實例。
//結構體
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");
}
}

