首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 多線程入門:Thread 類基礎用法

     編輯:關於C語言

核心命名空間

using System;
using System.Threading;

最簡單範例:兩條線程並發輸出

namespace ConsoleApplication1
{
    class Class1
    {
        [STAThread]
        static void Main(string[] args)
        {
            Thread thread1 = new Thread(new ThreadStart(Method1));
            Thread thread2 = new Thread(new ThreadStart(Method2));
            
            thread1.Start();
            thread2.Start();
            // 主線程結束不會自動結束子線程(前台線程)
            // 若需等待可用 thread1.Join() / thread2.Join()
        }

        public static void Method1()
        {
            while (true)
            {
                Console.WriteLine("this is thread : 1");
                Thread.Sleep(1000); // 休眠 1 秒
            }
        }

        public static void Method2()
        {
            while (true)
            {
                Console.WriteLine("this is thread : 2");
                Thread.Sleep(1520); // 休眠 1.52 秒
            }
        }
    }
}

關鍵概念

  • ThreadStart 委派:指向無參無返回值的方法
  • Start():將線程加入排程器,非同步返回
  • Sleep(ms):釋放 CPU 時間片,讓出執行權
  • 前台線程:預設 IsBackground = false,進程會等待所有前台線程結束
  • 後台線程:IsBackground = true,主線程結束時強制終止

常見模式擴展

帶參數線程

// ParameterizedThreadStart 接受 object 參數
Thread t = new Thread(obj => 
{
    int count = (int)obj;
    for (int i = 0; i < count; i++) Console.WriteLine(i);
});
t.Start(10);

Lambda 簡化語法

new Thread(() => 
{
    Console.WriteLine("Lambda thread running");
}).Start();

優雅停止

volatile bool _stop = false;
Thread t = new Thread(() => 
{
    while (!_stop) { /* work */ Thread.Sleep(100); }
});
t.Start();
// 別處調用 _stop = true; t.Join();

現代替代方案建議

  • Task / Task<T> (.NET 4.0+):ThreadPool 封裝、支援 await、異常傳播、取消令牌
  • Parallel.For/ForEach:資料並行
  • async/await:非阻塞非同步,而非多線程
  • BackgroundService / IHostedService:.NET Core 通用主機長運行任務

總結

Thread 類是 .NET 多線程的基石,理解其生命週期、同步原語、線程池關係至關重要。新專案優先考慮 Task 與 async/await,僅在需要精確控制線程身分(如 COM STA、專用線程名、實時性)時直接使用 Thread。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved