C#高階程式設計,給執行緒傳遞引數有兩種方式
一:使用ParameterizedThreadStart委託
如果使用了ParameterizedThreadStart委託,執行緒的入口必須有一個object型別方式一:使用ParameterizedThreadStart委託:
using System;
using System.Threading;
namespace ThreadWithParameters
{
class Program
{
static void Main(string[] args)
{
string hello = "hello world";
//這裡也可簡寫成Thread thread = new Thread(ThreadMainWithParameters);
//但是為了讓大家知道這裡用的是ParameterizedThreadStart委託,就沒有簡寫了
Thread thread = new Thread(new ParameterizedThreadStart(ThreadMainWithParameters));
thread.Start(hello);
Console.Read();
}
static void ThreadMainWithParameters(object obj)
{
string str = obj as string;
if(!string.IsNullOrEmpty(str))
Console.WriteLine("Running in a thread,received: {0}", str);
}
}
}
這裡稍微有點麻煩的就是ThreadMainWithParameters方法裡的引數必須是object型別的,我們需要進行型別轉換。
二:利用lambda表示式
using System.Threading;
namespace ThreadWithParameters
{
class Program
{
static void Main(string[] args)
{
string hello = "hello world";
//如果寫成Thread thread = new Thread(ThreadMainWithParameters(hello));這種形式,編譯時就會報錯
Thread thread = new Thread(() => ThreadMainWithParameters(hello));
thread.Start();
Console.Read();
}
static void ThreadMainWithParameters(string str)
{
Console.WriteLine("Running in a thread,received: {0}", str);
}
}
}