基本概念
Thread 是 .NET 中最基本的執行緒類別,用來讓程式同時執行多個工作(也就是所謂的「多執行緒」)。
命名空間:
using System.Threading;
基本用法範例
🔹 建立並啟動一個新執行緒
using System;
using System.Threading;
using System.Diagnostics;//for Debug.WriteLine
class Program
{
static void Main()
{
Thread t = new Thread(MyThread);
t.Start(); // 啟動執行緒
Debug.WriteLine("主執行緒繼續執行...");
}
static void MyThread()
{
Debug.WriteLine("這是來自新執行緒的訊息!");
}
}
傳遞參數給 Thread
方法一:使用 ParameterizedThreadStart
static void Main()
{
Thread t = new Thread(new ParameterizedThreadStart(MyThread));
t.Start("Hello from thread!");
}
static void MyThread(object msg)
{
Debug.WriteLine(msg);
}
方法二:使用 Lambda 表達式(推薦)
static void Main()
{
Thread t = new Thread(() => {
Debug.WriteLine("這是 Lambda 表達式中的執行緒!");
});
t.Start();
}
Thread.Join():等待執行緒完成
static void Main()
{
Thread t = new Thread(MyThreadMethod);
t.Start();
t.Join(); // 主執行緒會等待 t 執行完
Debug.WriteLine("子執行緒結束後,主執行緒才繼續。");
}
Thread.Sleep():讓出 CPU 一段時間
static void MyThreadMethod()
{
for (int i = 0; i < 5; i++)
{
Debug.WriteLine($"執行緒執行中... {i}");
Thread.Sleep(1000); // 暫停 1 秒
}
}
設定為背景執行緒(Background Thread)
Thread t = new Thread(MyThread);
t.IsBackground = true; // 程式結束時不會等待背景執行緒
t.Start();
留言
張貼留言