.NET 幫助

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

發佈 2024年3月6日
分享:

介紹

多執行緒是現代軟體開發中的一個關鍵方面,它允許開發人員同時執行多個任務,提高性能和響應能力。然而,有效地管理執行緒需要仔細考慮同步和協調。在 C# 開發人員的工具中,有一個管理執行緒計時和協調的重要工具就是 Thread.Sleep() 方法。

在本文中,我們將深入探討 Thread.Sleep 的複雜性() 方法,探討其目的、用法、潛在陷阱及替代方案。此外,在本文中,我們介紹了 IronPDF, C# PDF 庫由 Iron Software,方便程式化生成 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
VB   C#

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
VB   C#

在上面的程式範例中,我們在 while 迴圈裡有一個簡單的交通信號燈模擬。Thread.Sleep() 該方法用於在交通信號燈轉換之間引入延遲。以下是範例的工作方式:

  1. 程式進入一個無限循環以模擬持續運行。

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

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

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

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

輸出

C# Thread Sleep 方法(它對開發人員的作用):圖 1 - 程式輸出:使用 Thread.Sleep() 方法顯示交通信號燈模擬。

此例子演示了如何使用Thread.Sleep() 可用來控制交通燈模擬的時間,提供簡單的方法來建模現實世界系統的行為。請記住,這是一個基本示例,僅供說明之用,在更複雜的應用中,您可能需要探索更高級的多執行緒和同步技術來處理用戶輸入、管理多個交通燈並確保準確的時間安排。

使用時間區間超時在 Sleep 方法中

您可以在 Thread.Sleep 中使用 TimeSpan() 方法來指定休眠時間。以下是一個延伸前例交通信號模擬的範例,使用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
VB   C#

在這個修改過的範例中, 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()
VB   C#
  1. 動畫和 UI 更新: 在圖形 Web 開發應用程序或遊戲開發中,平滑的動畫和 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()
VB   C#
  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()
VB   C#

Thread.Sleep 的優點()

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

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

  3. 簡單性和可讀性: 該方法提供了一種簡單且可讀的方式來引入延遲,使代碼更易於理解,尤其是對於剛接觸多線程概念的開發人員。

潛在陷阱與考量

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

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

  2. 時間的不準確性: 暫停時長的準確性取決於底層操作系統的排程,可能不會精確。開發人員應該在依賴 Thread.Sleep 時保持謹慎()`精確計時需求。

  3. 替代方法: 在現代 C# 開發中,諸如 Task.Delay 之類的替代方法()方法或使用async/await非同步程式設計通常比Thread.Sleep更受青睞(). 這些方法提供了更好的響應性而不會阻塞線程。
// 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
VB   C#

介紹 IronPDF

IronPDF由 Iron Software 開發,是一個 C# PDF 庫,既可以作為 PDF 生成器,也可以作為 PDF 閱讀器。本節介紹了基本功能。欲了解更多詳情,請參閱 文檔 頁面。

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
VB   C#

安裝

安裝 IronPDF,使用 NuGet 套件管理器控制台或 Visual Studio 套件管理器。

使用 NuGet 套件管理器控制台安裝 IronPDF 庫,使用以下其中一個命令:

dotnet add package IronPdf
# or
Install-Package IronPdf

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

C# 线程休眠方法(它是如何为开发人员工作的):圖 2 - 使用 NuGet 套件管理器安裝 IronPDF,通過在 NuGet 套件管理器的搜索欄中搜索「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
VB   C#

在這個程式中,我們演示如何使用Thread.Sleep和IronPDF。程式首先驗證一個人的firstnamelastname屬性。然後在控制台上列印這個人的全名。接著使用Thread.Sleep等待2秒,然後使用PrintPdffullname列印到PDF中。()` 方法與IronPDF函式庫。

輸出

C# 執行緒暫停方法(開發者如何使用):圖 3 - 主控台輸出:顯示在使用 IronPDF 生成 PDF 時使用 Thread.Sleep。

生成的 PDF

C# Thread Sleep 方法(開發人員如何使用):圖4 - 已創建的輸出 PDF。

授權 (免費試用)

要使用 IronPDF將此密鑰插入appsettings.json文件。

"IronPdf.LicenseKey": "your license key"
"IronPdf.LicenseKey": "your license key"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'"IronPdf.LicenseKey": "your license key"
VB   C#

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

結論

Thread.Sleep()方法在 C# 中是管理線程時序和同步的基本工具。雖然這是一個簡單而有效的引入延遲的解決方案,但開發人員應注意其限制以及對應用程式性能可能產生的影響。隨著現代 C# 開發的演變,探索像 Task.Delay() 非同步程式設計對於撰寫回應迅速且高效的多執行緒應用程式至關重要。透過理解執行緒同步的細微差別並選擇適當的工具,開發人員可以建立穩健且高效的軟體,以滿足動態環境中同時處理的需求。

此外,我們觀察到了其多樣性 IronPDF 在生成 PDF 文件的過程中使用這個程式庫,以及如何與 Thread.Sleep 方法一起使用。欲了解更多有關 IronPDF 的使用範例,請參閱他們的代碼範例。 頁面.

< 上一頁
C# Null 條件運算子(開發人員如何運作)
下一個 >
C# 常數(它如何為開發者運作)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >