接觸C#和VS也差不多五個月了,其實也還是個小白,關(guān)于線程的用法其實在網(wǎng)上找又一大堆,無形參無返回,無形參有返回,有形參無返回,有形參有返回的四種情況,簡單的總結(jié)一下我使用過的方法吧~
1.無形參無返回
Thread thread = new Thread(doWork);
thread.start();
2.無形參有返回
(這里的栗子是,doThread返回一個bool值)
public delegate bool MyDelegate();//根據(jù)doThread的返回類型聲明一個委托
private void delegateThread()
{
MyDelegate dele = new MyDelegate(doWork);//委托,但是還是還會在主線程上處理
bool result = dele.Invoke(); //收集返回值
}
private void doThread()
{
Control.CheckForIllegalCrossThreadCalls = false;//防止獲取界面控件是拋出的異常
Thread thread = new Thread(new ThreadStart(delegateThread));
thread.Priority = ThreadPriority.Highest;//優(yōu)先級
thread.IsBackground = true;//與程序共存亡
thread.Start();
}
3.有形參無返回
Control.CheckForIllegalCrossThreadCalls = false;
ThreadStart starter = delegate { doWork(parameter); };//parameter就是填入的參數(shù)
Thread thread= new Thread(new ThreadStart(starter));
thread.IsBackground = true;
thread.Start();
4.有形參有返回
(這里的栗子是,doThread一個int型的形參是,返回一個int值)
其實跟2.無形參有返回 差不多,都是用一個委托函數(shù)包起來。還有可以用一個類,把你的方法和成員變量包起來用也是一樣可以的。我這里就說一種方法吧。
public delegate int MyDelegate(int a);
static void Main(string[] args)
{
Thread thread;
thread = new Thread(new ThreadStart(delegateThread));
thread.Start();
thread.IsBackground = true;
Console.ReadLine();
}
private static void delegateThread()
{
MyDelegate dele = new MyDelegate(doWork);
int result = dele.Invoke(3); //收集返回值
Console.WriteLine("result:" + result);
}
private static int doWork(int num)
{
Console.WriteLine("doWork!\n");
return num * num;
}
其實每種情況都有多種實現(xiàn)的方法,這里就只介紹下我用過的,可能有些欠缺的地方,歡迎指點~