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

多線程入門系列(三):線程優先級與排程影響

     編輯:關於C#

ThreadPriority 列舉

優先級數值說明
Lowest0最低,僅在系統閒置時執行
BelowNormal1低於正常
Normal2預設,標準優先級
AboveNormal3高於正常
Highest4最高,搶佔性最強

優先級影響機制

  • 作業系統排程器根據優先級分配 CPU 時間片。
  • 高優先級線程可搶佔低優先級線程。
  • 非即時系統:Windows 非硬性即時 OS,優先級僅影響機率,不保證執行順序。
  • 進程優先級(ProcessPriorityClass)與線程優先級疊加決定最終有效優先級。

設定與讀取範例

using System;
using System.Threading;

class PriorityDemo
{
    static int lowCount = 0, highCount = 0;
    static bool stop = false;
    
    static void Main()
    {
        Thread low = new Thread(() => { while (!stop) lowCount++; }) { Priority = ThreadPriority.Lowest };
        Thread high = new Thread(() => { while (!stop) highCount++; }) { Priority = ThreadPriority.Highest };
        
        low.Start();
        high.Start();
        
        Thread.Sleep(2000);
        stop = true;
        low.Join(); high.Join();
        
        Console.WriteLine("Lowest: {0:N0}", lowCount);
        Console.WriteLine("Highest: {0:N0}", highCount);
        Console.WriteLine("比率: {0:F1}:1", (double)highCount / lowCount);
    }
}

典型輸出:Highest 計數遠高於 Lowest,但比率受 CPU 核心數、其他進程干擾影響。

進程優先級類別

ProcessPriorityClass說明
Idle僅在系統閒置執行
BelowNormal低於標準
Normal預設
AboveNormal高於標準
High高優先級
RealTime最高,可能導致系統卡頓,慎用
using System.Diagnostics;
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.AboveNormal;

實務建議

  1. 預設用 Normal:絕大多數情況無需調整。
  2. 背景非關鍵工作:可設 BelowNormal 或 Lowest(如定期清理、索引建立)。
  3. 即時回應需求:AboveNormal 或 Highest(如音訊播放、輸入處理),但慎防餓死其他線程。
  4. 避免 RealTime 進程:除非專用嵌入式環境,否則可能導致滑鼠/鍵盤無回應。
  5. 測試驗證:優先級調整必須在目標環境實測,理論值參考有限。

圖示說明

(原文包含五張圖片,展示優先級列舉、排程器運作、進程/線程優先級疊加、實測程式碼、結果分析)

ThreadPriority 列舉 排程器時間片分配 進程與線程優先級疊加 優先級實測程式碼 實測結果分析
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved