.NET 帮助

C# 线程睡眠方法(开发人员如何使用)

发布 2024年三月6日
分享:

简介

多线程是现代软件开发的一个重要方面,它允许开发人员同时执行多个任务,从而提高性能和响应速度。然而,有效管理线程需要仔细考虑同步和协调问题。C# 开发人员管理线程定时和协调的一个重要工具是 Thread.Sleep() 方法。

在本文中,我们将深入探讨 Thread.Sleep 方法的复杂性。() 方法,探讨其目的、用法、潜在缺陷和替代方法。此外,我们还在本文中介绍了 IronPDFC# 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
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# 线程睡眠方法(开发人员如何使用):图 1 - 程序输出:使用 Thread.Sleep() 方法显示交通灯模拟器。

本例演示了 Thread.Sleep() 可用于控制交通灯模拟的定时,提供了一种模拟真实世界系统行为的简单方法。请记住,这只是一个用于说明的基本示例,在更复杂的应用中,您可能需要探索更高级的线程和同步技术,以处理用户输入、管理多个交通信号灯并确保计时准确。

在睡眠方法中使用 Timespan 超时

您可以在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. 动画和用户界面更新: 在图形网络开发应用程序或游戏开发中,流畅的动画和用户界面更新至关重要。线程睡眠()可用于控制帧频,确保以视觉上令人愉悦的速度进行更新。
// 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 交互时,通常会施加速率限制或节流以防止请求过多。线程睡眠()可在不超出费率限制的情况下,在连续服务呼叫之间引入延迟。
// 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是一个 C# PDF 库,既可用作 PDF 生成器,也可用作 PDF 阅读器。本节将介绍其基本功能。有关详细信息,请查阅 文献资料 page.

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# 线程睡眠方法(开发人员如何使用):图 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 许可证的更多信息,请访问此处 许可证页面.

结论

线程.睡眠()C# 中的 方法是管理线程定时和同步的基本工具。虽然它是引入延迟的简单而有效的解决方案,但开发人员应注意其局限性和对应用程序性能的潜在影响。随着现代 C# 开发的发展,探索其他方法(如Task.Delay()异步编程对于编写反应灵敏、高效的多线程应用程序至关重要。通过了解线程同步的细微差别并选择适当的工具,开发人员可以创建稳健高效的软件,满足动态环境中并发处理的需求。

此外,我们还观察到了线程同步的多功能性。 IronPDF 库在生成 PDF 文档中的作用,以及如何将其与 Thread.Sleep 方法一起使用。有关如何使用 IronPDF 的更多示例,请访问其代码示例 页码.

< 前一页
C#空条件运算符(开发人员如何使用)
下一步 >
C# 常量(开发人员如何使用)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >