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

C# 基礎語法:執行緒(Thread) 入門與同步鎖定實作

     編輯:關於C語言

單一執行緒基本範例

using System;
using System.Threading;

class SingleThread
{
    static void Main(string[] args)
    {
        SingleThread st = new SingleThread();
        Thread th = new Thread(new ThreadStart(st.SayHello));
        th.Start();
    }

    public void SayHello()
    {
        Console.WriteLine("Hello from a single thread.");
    }
}

多執行緒同步資料存取

class SyncData
{
    int index = 0;
    string[] comments = { "一", "二", "三", "四", "五", "六", "七", "八", "九", "十",
                          "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十" };

    public string GetNextComment()
    {
        lock (this)
        {
            if (index < comments.Length)
                return comments[index++];
            return "empty";
        }
    }
}

class Synchronization
{
    SyncData data = new SyncData();

    public void GetComments()
    {
        string comment;
        do
        {
            comment = data.GetNextComment();
            Console.WriteLine($"Current Thread: {Thread.CurrentThread.Name}, Comment: {comment}");
        } while (comment != "empty");
    }

    static void Main(string[] args)
    {
        Synchronization sync = new Synchronization();
        Thread t1 = new Thread(new ThreadStart(sync.GetComments)) { Name = "Thread 1" };
        Thread t2 = new Thread(new ThreadStart(sync.GetComments)) { Name = "Thread 2" };
        Thread t3 = new Thread(new ThreadStart(sync.GetComments)) { Name = "Thread 3" };

        t1.Start(); t2.Start(); t3.Start();
    }
}

核心概念總結

概念說明
ThreadStart無參數無回傳值的委派,指向執行緒進入點方法
lock互斥鎖,確保同一時間只有一個執行緒進入關鍵區段
Thread.CurrentThread.Name設定/取得執行緒名稱,方便除錯追蹤
Start()啟動執行緒,排程執行但不保證立即執行

進階建議

  • 優先使用 Task / async-await 取代手動管理 Thread
  • 共享資料使用 Concurrent 集合或 ReaderWriterLockSlim
  • 避免在 lock 區塊內執行耗時操作
  • 考慮使用 CancellationToken 實作優雅取消
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved