.NET 幫助

C# Thread Sleep 方法(對開發人員的運作方式)

介紹

多執行緒是現代軟體開發的一個關鍵方面,能夠讓開發人員同時執行多個任務,提高性能和響應速度。 然而,有效地管理執行緒需要仔細考量同步與協調。 在 C# 開發者的工具箱中,用於管理線程計時和協調的一個基本工具是 Thread.Sleep() 方法。

在本文中,我們將深入探討 Thread.Sleep() 方法的複雜性,分析其目的、用法、可能的缺陷及替代方案。 此外,在本文中,我們介紹了IronPDF C# PDF 庫,該庫可促進 PDF 文件的程式生成。

了解 Thread.Sleep()

Thread.Sleep() 方法 是 C# 中 System.Threading 命名空間的一部分,用於在指定的時間內阻止當前執行緒的執行。等待中的執行緒或被阻止的執行緒會停止執行,直到指定的休眠時間結束為止。Sleep 方法接受一個參數,表示執行緒應保持不活動的時間間隔。此參數可以以毫秒為單位指定,也可以作為 TimeSpan 對象指定,這提供了表示所需暫停時間的靈活性。

// Using Thread.Sleep() with a specified number of milliseconds
Thread.Sleep(1000); // block for 1 second
// Using Thread.Sleep() with TimeSpan
TimeSpan sleepDuration = TimeSpan.FromSeconds(2);
Thread.Sleep(sleepDuration); // block for 2 seconds
// Using Thread.Sleep() with a specified number of milliseconds
Thread.Sleep(1000); // block for 1 second
// Using Thread.Sleep() with TimeSpan
TimeSpan sleepDuration = TimeSpan.FromSeconds(2);
Thread.Sleep(sleepDuration); // block for 2 seconds
' Using Thread.Sleep() with a specified number of milliseconds
Thread.Sleep(1000) ' block for 1 second
' Using Thread.Sleep() with TimeSpan
Dim sleepDuration As TimeSpan = TimeSpan.FromSeconds(2)
Thread.Sleep(sleepDuration) ' block for 2 seconds
$vbLabelText   $csharpLabel

Thread.Sleep 的目的

使用Thread.Sleep的主要目的是在執行緒的執行過程中引入延遲或暫停。 這在各種情境中都可能有益,例如:

  1. 模擬即時行為:在應用程序需要模擬即時行為的情況下,引入延遲可以幫助模仿所建模系統的時序限制。

  2. 防止過度資源消耗: 暫停一個執行緒的短時間運行在不需要連續執行的情況下非常有用,這樣可以防止不必要的資源消耗。

  3. 執行緒協調: 在處理多個執行緒時,引入暫停可以幫助同步它們的執行,防止競爭條件並確保有序處理。

真實世界範例

讓我們考慮一個現實世界的例子,Thread.Sleep() 方法可用於模擬一個交通信號控制系統。 在此情境中,我們將創建一個簡單的控制台應用程式,模擬紅燈、黃燈和綠燈信號的交通燈行為。

using System .Threading;
public class TrafficLightSimulator
{
    static void Main()
    {
        Console.WriteLine("Traffic Light Simulator");
        while (true)
        {
            // Display the red light
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine($"Stop! Red light - {DateTime.Now.ToString("u")}");
            Thread.Sleep(5000); // Pause for 5 seconds and start execution
            // Display the yellow light
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine($"Get ready! Yellow light - {DateTime.Now.ToString("u")}");
            Thread.Sleep(2000); // Pause for 2 seconds
            // Display the green light
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"Go! Green light - {DateTime.Now.ToString("u")}");
            Thread.Sleep(5000); // Pause for 5 seconds
            // Reset console color
            Console.ResetColor();
            Console.Clear();
        }
    }
}
using System .Threading;
public class TrafficLightSimulator
{
    static void Main()
    {
        Console.WriteLine("Traffic Light Simulator");
        while (true)
        {
            // Display the red light
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine($"Stop! Red light - {DateTime.Now.ToString("u")}");
            Thread.Sleep(5000); // Pause for 5 seconds and start execution
            // Display the yellow light
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine($"Get ready! Yellow light - {DateTime.Now.ToString("u")}");
            Thread.Sleep(2000); // Pause for 2 seconds
            // Display the green light
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"Go! Green light - {DateTime.Now.ToString("u")}");
            Thread.Sleep(5000); // Pause for 5 seconds
            // Reset console color
            Console.ResetColor();
            Console.Clear();
        }
    }
}
Imports System.Threading
Public Class TrafficLightSimulator
	Shared Sub Main()
		Console.WriteLine("Traffic Light Simulator")
		Do
			' Display the red light
			Console.ForegroundColor = ConsoleColor.Red
			Console.WriteLine($"Stop! Red light - {DateTime.Now.ToString("u")}")
			Thread.Sleep(5000) ' Pause for 5 seconds and start execution
			' Display the yellow light
			Console.ForegroundColor = ConsoleColor.Yellow
			Console.WriteLine($"Get ready! Yellow light - {DateTime.Now.ToString("u")}")
			Thread.Sleep(2000) ' Pause for 2 seconds
			' Display the green light
			Console.ForegroundColor = ConsoleColor.Green
			Console.WriteLine($"Go! Green light - {DateTime.Now.ToString("u")}")
			Thread.Sleep(5000) ' Pause for 5 seconds
			' Reset console color
			Console.ResetColor()
			Console.Clear()
		Loop
	End Sub
End Class
$vbLabelText   $csharpLabel

在上面的程式範例中,我們在 while 迴圈內進行了一個簡單的交通燈模擬。使用 Thread.Sleep() 方法來引入交通燈信號變換之間的延遲。 以下是範例的工作原理:

  1. 程式進入無限迴圈以模擬持續運行。

  2. 紅燈顯示5秒,代表停止信號。

  3. 5秒後,黃色燈亮起2秒,表示準備階段。

  4. 最後,綠燈顯示5秒鐘,允許車輛通行。

  5. 控制台顏色重置,然後循環重複。

輸出

C# Thread Sleep 方法(開發人員如何使用):圖 1 - 程式輸出:使用 Thread.Sleep() 方法顯示交通燈模擬器。

此範例展示了如何使用 Thread.Sleep() 來控制紅綠燈模擬的時序,提供了一種簡單的方式來模擬現實系統的行為。 請注意,這是一個用於說明用途的基本範例。在更複雜的應用中,您可能需要探索更先進的執行緒和同步技術來處理用戶輸入、管理多個交通信號燈以及確保精確的計時。

在 Sleep 方法中使用 Timespan Timeout

您可以使用TimeSpan與Thread.Sleep()方法來指定休眠持續時間。 以下是一個使用 TimeSpan 擴展前一個例子的交通燈模擬的示例:

using System;
using System.Threading;
class TrafficLightSimulator
{
    public static void Main()
    {
        Console.WriteLine("Traffic Light Simulator");
        while (true)
        {
            // Display the red light
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Stop! Red light- {DateTime.Now.ToString("u")}");
            Thread.Sleep(TimeSpan.FromSeconds(5)); // Pause for 5 seconds
            // Display the yellow light
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Get ready! Yellow light-     {DateTime.Now.ToString("u")}");
            Thread.Sleep(TimeSpan.FromSeconds(2)); // Pause for 2 seconds
            // Display the green light
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Go! Green light- {DateTime.Now.ToString("u")}");
            Thread.Sleep(TimeSpan.FromSeconds(5)); // Pause for 5 seconds
            // Reset console color
            Console.ResetColor();
            Console.Clear();
        }
    }
}
using System;
using System.Threading;
class TrafficLightSimulator
{
    public static void Main()
    {
        Console.WriteLine("Traffic Light Simulator");
        while (true)
        {
            // Display the red light
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Stop! Red light- {DateTime.Now.ToString("u")}");
            Thread.Sleep(TimeSpan.FromSeconds(5)); // Pause for 5 seconds
            // Display the yellow light
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Get ready! Yellow light-     {DateTime.Now.ToString("u")}");
            Thread.Sleep(TimeSpan.FromSeconds(2)); // Pause for 2 seconds
            // Display the green light
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Go! Green light- {DateTime.Now.ToString("u")}");
            Thread.Sleep(TimeSpan.FromSeconds(5)); // Pause for 5 seconds
            // Reset console color
            Console.ResetColor();
            Console.Clear();
        }
    }
}
Imports System
Imports System.Threading
Friend Class TrafficLightSimulator
	Public Shared Sub Main()
		Console.WriteLine("Traffic Light Simulator")
		Do
			' Display the red light
			Console.ForegroundColor = ConsoleColor.Red
			Console.WriteLine("Stop! Red light- {DateTime.Now.ToString("u")}")
			Thread.Sleep(TimeSpan.FromSeconds(5)) ' Pause for 5 seconds
			' Display the yellow light
			Console.ForegroundColor = ConsoleColor.Yellow
			Console.WriteLine("Get ready! Yellow light-     {DateTime.Now.ToString("u")}")
			Thread.Sleep(TimeSpan.FromSeconds(2)) ' Pause for 2 seconds
			' Display the green light
			Console.ForegroundColor = ConsoleColor.Green
			Console.WriteLine("Go! Green light- {DateTime.Now.ToString("u")}")
			Thread.Sleep(TimeSpan.FromSeconds(5)) ' Pause for 5 seconds
			' Reset console color
			Console.ResetColor()
			Console.Clear()
		Loop
	End Sub
End Class
$vbLabelText   $csharpLabel

在這個修改後的範例中,TimeSpan.FromSeconds() 用於創建一個代表所需休眠時間的 TimeSpan 物件。 這使代碼更具可讀性和表達性。

通過在 Thread.Sleep() 方法中使用 TimeSpan 屬性,您可以直接以秒(或 TimeSpan 支援的任何其他單位)指定持續時間,提供了一種更直觀的方式來處理時間間隔。 這在處理應用程式中較長或更複雜的休眠時間時特別有用。

使用案例

  1. 模擬即時行為:考慮一個需要模擬即時系統行為的模擬應用程式。 透過在程式碼中策略性地放置Thread.Sleep(),您可以模擬實際系統中發生的時間延遲,增強模擬的準確性。
// Simulating real-time behavior with Thread.Sleep()
SimulateRealTimeEvent();
Thread.Sleep(1000); // Pause for 1 second
SimulateNextEvent();
// Simulating real-time behavior with Thread.Sleep()
SimulateRealTimeEvent();
Thread.Sleep(1000); // Pause for 1 second
SimulateNextEvent();
' Simulating real-time behavior with Thread.Sleep()
SimulateRealTimeEvent()
Thread.Sleep(1000) ' Pause for 1 second
SimulateNextEvent()
$vbLabelText   $csharpLabel
  1. 動畫和 UI 更新:在圖形化網頁開發應用程式或遊戲開發中,流暢的動畫和 UI 更新至關重要。 Thread.Sleep() 可以用來控制幀率,確保更新以視覺上令人滿意的速度發生。
// Updating UI with controlled delays
UpdateUIElement();
Thread.Sleep(50); // Pause for 50 milliseconds
UpdateNextUIElement();
// Updating UI with controlled delays
UpdateUIElement();
Thread.Sleep(50); // Pause for 50 milliseconds
UpdateNextUIElement();
' Updating UI with controlled delays
UpdateUIElement()
Thread.Sleep(50) ' Pause for 50 milliseconds
UpdateNextUIElement()
$vbLabelText   $csharpLabel
  1. 限制外部服務調用: 與外部服務或 API 互動時,常見的做法是設置速率限制或節流,以防止過多的請求。 Thread.Sleep() 可以用來在連續的服務呼叫之間引入延遲,以保持在速率限制之內。
// Throttling service calls with Thread.Sleep()
CallExternalService();
Thread.Sleep(2000); // Pause for 2 seconds before the next call
CallNextService();
// Throttling service calls with Thread.Sleep()
CallExternalService();
Thread.Sleep(2000); // Pause for 2 seconds before the next call
CallNextService();
' Throttling service calls with Thread.Sleep()
CallExternalService()
Thread.Sleep(2000) ' Pause for 2 seconds before the next call
CallNextService()
$vbLabelText   $csharpLabel

Thread.Sleep() 的優點

  1. 同步與協調:Thread.Sleep()有助於同步執行緒的運行,防止競爭條件,並確保在處理多個執行緒時的有序處理。

  2. 資源節約: 在不需要持續執行的情況下暫停執行緒可以是有利的,有助於節約系統資源。

  3. 簡單性和可讀性:該方法提供了一種簡單且易讀的方式來引入延遲,這使代碼更易於理解,特別是對於對多執行緒概念不太熟悉的開發者。

潛在的陷阱與考量

雖然Thread.Sleep()是一個引入延遲的簡單解決方案,但開發人員應注意潛在的陷阱和考慮事項:

  1. 阻塞執行緒: 當使用 Thread.Sleep() 暫停執行緒時,它會被有效地阻塞,此期間無法執行其他工作。在響應性至關重要的情況下,長時間阻塞主執行緒可能會導致不佳的用戶體驗。

  2. 計時不準確:暫停時間的準確性取決於底層操作系統的調度,可能不精確。開發人員在依賴Thread.Sleep()進行精確計時時應謹慎。

  3. 替代方法:在現代 C# 開發中,比起 Thread.Sleep(),通常更偏好使用像 Task.Delay() 方法或者使用 async/await 的異步編程。 這些方法提高了響應性而不阻塞執行緒。
// Using Task.Delay() instead of Thread.Sleep()
await Task.Delay(1000); // Pause for 1 second asynchronously
// Using Task.Delay() instead of Thread.Sleep()
await Task.Delay(1000); // Pause for 1 second asynchronously
' Using Task.Delay() instead of Thread.Sleep()
Await Task.Delay(1000) ' Pause for 1 second asynchronously
$vbLabelText   $csharpLabel

介紹 IronPDF

IronPDF by Iron Software 是一個 C# PDF 函式庫,同時充當 PDF 生成器和閱讀器。 本節介紹基本功能。 如需進一步詳細資訊,請參閱IronPDF 文件

IronPDF 的亮點在於其HTML 轉換為 PDF 的能力,確保所有佈局和樣式得以保留。 將網頁內容轉換為PDF,對報告、發票和文檔非常有用。 HTML 文件、URL 和 HTML 字串可以輕鬆轉換為 PDF。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

安裝

要安裝使用NuGet套件管理器安裝IronPDF,可以使用NuGet套件管理器主控台或Visual Studio套件管理器。

使用以下命令之一透過 NuGet 套件管理器主控台安裝 IronPDF 庫:

dotnet add package IronPdf
# or
Install-Package IronPdf
dotnet add package IronPdf
# or
Install-Package IronPdf
SHELL

使用 Visual Studio 的套件管理器安裝 IronPDF 庫:

C# Thread Sleep Method(如何為開發人員工作):圖2 - 使用NuGet Package Manager安裝IronPDF,通過在NuGet Package Manager的搜索欄中搜索「ironpdf」。

using System;
using IronPdf;
class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public void DisplayFullName()
    {
        if (string.IsNullOrEmpty(FirstName) 
 string.IsNullOrEmpty(LastName))
        {
            LogError($"Invalid name: {nameof(FirstName)} or {nameof(LastName)} is missing.");
        }
        else
        {
            Console.WriteLine($"Full Name: {FirstName} {LastName}");
        }
    }
    public void PrintPdf()
    {
        Console.WriteLine("Generating PDF using IronPDF.");
        string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {FirstName}!</h1>
<p>First Name: {FirstName}</p>
<p>First Name: {LastName}</p>
</body>
</html>";
        // Create a new PDF document
        var pdfDocument = new ChromePdfRenderer();
        pdfDocument.RenderHtmlAsPdf(content).SaveAs("person.pdf");
    }
    private void LogError(string errorMessage)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine($"Error: {errorMessage}");
        Console.ResetColor();
    }
}
class Program
{
    public static void Main()
    {
        // Create an  instance of the Person class
        Person person = new Person();
        // Attempt to display the full name
        person.DisplayFullName();
        // Set the properties
        person.FirstName = "John"; // string literal
        person.LastName = "Doe"; // string literal
        // Display the full name again
        person.DisplayFullName();
        Console.WriteLine("Pause for 2 seconds and Print PDF");
        Thread.Sleep(2000); // Pause for 2 seconds and Print PDF
        // Print the full name to PDF
        person.PrintPdf();
    }
}
using System;
using IronPdf;
class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public void DisplayFullName()
    {
        if (string.IsNullOrEmpty(FirstName) 
 string.IsNullOrEmpty(LastName))
        {
            LogError($"Invalid name: {nameof(FirstName)} or {nameof(LastName)} is missing.");
        }
        else
        {
            Console.WriteLine($"Full Name: {FirstName} {LastName}");
        }
    }
    public void PrintPdf()
    {
        Console.WriteLine("Generating PDF using IronPDF.");
        string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {FirstName}!</h1>
<p>First Name: {FirstName}</p>
<p>First Name: {LastName}</p>
</body>
</html>";
        // Create a new PDF document
        var pdfDocument = new ChromePdfRenderer();
        pdfDocument.RenderHtmlAsPdf(content).SaveAs("person.pdf");
    }
    private void LogError(string errorMessage)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine($"Error: {errorMessage}");
        Console.ResetColor();
    }
}
class Program
{
    public static void Main()
    {
        // Create an  instance of the Person class
        Person person = new Person();
        // Attempt to display the full name
        person.DisplayFullName();
        // Set the properties
        person.FirstName = "John"; // string literal
        person.LastName = "Doe"; // string literal
        // Display the full name again
        person.DisplayFullName();
        Console.WriteLine("Pause for 2 seconds and Print PDF");
        Thread.Sleep(2000); // Pause for 2 seconds and Print PDF
        // Print the full name to PDF
        person.PrintPdf();
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

在本程式中,我們展示如何使用Thread.Sleep和IronPDF。 該程式碼最初驗證一個人的FirstNameLastName屬性。 然後在控制台上打印該人的全名。 然後使用Thread.Sleep等待2秒,隨後使用PrintPdf()方法和IronPDF庫將FullName列印至PDF。

輸出

C# Thread Sleep Method(開發者如何運作):圖 3 - 主控台輸出:顯示在使用 IronPDF 生成 PDF 時 Thread.Sleep 的使用。

生成的 PDF

C# Thread Sleep 方法(對開發者的運作方式):圖4 - 創建的輸出 PDF。

授權(免費試用可用)

要使用 IronPDF,請將此金鑰插入到 appsettings.json 文件中。

"IronPdf.LicenseKey": "your license key"

要獲取試用許可證,請提供您的電子郵件。 如需有關IronPDF授權的更多資訊,請造訪此IronPDF授權頁面

結論

C# 中的 Thread.Sleep() 方法作為管理執行緒定時和同步的基本工具。 儘管這是一個簡單且有效的延遲解決方案,開發人員仍應注意其限制以及對應用程式效能的潛在影響。 隨著現代 C# 開發的演變,探索類似 Task.Delay() 和異步編程的替代方法對於編寫響應迅速且高效的多執行緒應用程式變得至關重要。 透過了解線程同步的細微差別並選擇合適的工具,開發人員可以創建出滿足動態環境中並發處理需求的強大且高效的軟體。

此外,我們觀察到了IronPDF 功能的多樣性,在生成 PDF 文件和如何與 Thread.Sleep 方法一起使用。 欲了解更多有關如何使用IronPDF的範例,請造訪其IronPDF範例頁面查看其代碼範例。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
C# Null 條件運算子(開發人員如何運作)
下一個 >
C# 常數(它如何為開發者運作)