
C# 等待几秒钟(开发者如何使用)
在编程中,有时您会希望暂停或延迟代码的执行一定的时间。这是为了模拟不同的时间条件,优先处理某些任务,在不阻塞主线程的情况下执行其他任务等。
在本指南中,我们将解释如何在C#中实现等待,包括异步方法、休眠命令、休眠函数、控制台应用程序,以及如何在我们领先的PDF生成工具IronPDF中加入等待功能。
如何在C#中等待任务
休眠命令
'休眠'是一个简单但强大的命令,它允许您暂停当前任务的执行指定的时间,本质上是告诉程序等待,然后再进行下一个任务。 在C#中,我们通过使用Thread.Sleep(int milliseconds)方法来实现,如以下代码示例所示:
using System;
using System.Threading;
class Program
{
public static void Main()
{
Console.WriteLine("Starting the program...");
Thread.Sleep(3000); // Sleep for 3 seconds
Console.WriteLine("...Program continues after 3 seconds");
}
}Imports System
Imports System.Threading
Class Program
Public Shared Sub Main()
Console.WriteLine("Starting the program...")
Thread.Sleep(3000) ' Sleep for 3 seconds
Console.WriteLine("...Program continues after 3 seconds")
End Sub
End Class在这里,程序开始时会在使用Thread.Sleep方法暂停3,000毫秒(三秒)之前,先在控制台打印"启动程序..." 在指定的延迟后,程序恢复并在控制台打印输出"...程序在3秒后继续"。
异步方法和任务
C#中的异步方法使您能够同时执行多个任务而不干扰主线程。 这意味着在一个任务等待时,其他任务可以继续运行。 要实现一个异步方法,需要使用Task类。
using System;
using System.Threading.Tasks;
class Program
{
public static async Task Main()
{
Console.WriteLine("Starting Task 1...");
var task1 = DoSomethingAsync(3000);
Console.WriteLine("Starting Task 2...");
var task2 = DoSomethingAsync(2000);
await Task.WhenAll(task1, task2);
Console.WriteLine("Both tasks completed.");
}
private static async Task DoSomethingAsync(int milliseconds)
{
await Task.Delay(milliseconds); // Asynchronously wait without blocking the main thread
Console.WriteLine($"Task completed after {milliseconds} milliseconds");
}
}Imports System
Imports System.Threading.Tasks
Friend Class Program
Public Shared Async Function Main() As Task
Console.WriteLine("Starting Task 1...")
Dim task1 = DoSomethingAsync(3000)
Console.WriteLine("Starting Task 2...")
Dim task2 = DoSomethingAsync(2000)
Await Task.WhenAll(task1, task2)
Console.WriteLine("Both tasks completed.")
End Function
Private Shared Async Function DoSomethingAsync(ByVal milliseconds As Integer) As Task
Await Task.Delay(milliseconds) ' Asynchronously wait without blocking the main thread
Console.WriteLine($"Task completed after {milliseconds} milliseconds")
End Function
End Class在这个代码示例中,我们有两个任务同时运行。2000所示,都是超时值)。 Thread.Sleep()方法,但它处理异步任务且不阻塞主线程。
使用计时器来调度任务
C#中的计时器允许您在指定的时间间隔后执行特定任务。 可以使用System.Timers.Timer类创建计时器。 以下是在控制台应用程序中使用计时器的示例:
using System;
using System.Timers;
class Program
{
public static void Main()
{
var timer = new Timer(1000); // Create a timer with a 1-second interval
timer.Elapsed += OnTimerElapsed;
timer.AutoReset = true;
timer.Enabled = true;
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
private static void OnTimerElapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("Timer ticked at " + e.SignalTime);
}
}Imports System
Imports System.Timers
Class Program
Public Shared Sub Main()
Dim timer As New Timer(1000) ' Create a timer with a 1-second interval
AddHandler timer.Elapsed, AddressOf OnTimerElapsed
timer.AutoReset = True
timer.Enabled = True
Console.WriteLine("Press any key to exit...")
Console.ReadKey()
End Sub
Private Shared Sub OnTimerElapsed(sender As Object, e As ElapsedEventArgs)
Console.WriteLine("Timer ticked at " & e.SignalTime)
End Sub
End Class在上述示例中,我们创建了一个1秒间隔的计时器。 每次计时器触发时,都会执行OnTimerElapsed方法。 我们将AutoReset属性设置为true,以便计时器在每次触发后自动重启。 Enabled属性设置为true以启动计时器。
当您运行该控制台应用程序时,您将看到计时器每秒计时一次,并在控制台上打印计时时间。 程序将继续运行,直到您按下任何键退出。
创建自定义等待函数
有时,您可能需要一个自定义等待函数以满足您代码中的特定要求。 例如,您可能希望创建一个仅阻塞当前任务而不是整个线程的等待函数。 您可以使用异步委托实现这一点。
以下是一个自定义等待函数的示例:
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
public static async Task Main()
{
Console.WriteLine("Starting Task 1...");
await CustomWaitAsync(3000);
Console.WriteLine("Task 1 completed.");
Console.WriteLine("Starting Task 2...");
await CustomWaitAsync(2000);
Console.WriteLine("Task 2 completed.");
}
private static async Task CustomWaitAsync(int milliseconds)
{
await Task.Run(() => Thread.Sleep(milliseconds)); // Run in a separate task to avoid blocking the main thread
}
}Imports System
Imports System.Threading
Imports System.Threading.Tasks
Friend Class Program
Public Shared Async Function Main() As Task
Console.WriteLine("Starting Task 1...")
Await CustomWaitAsync(3000)
Console.WriteLine("Task 1 completed.")
Console.WriteLine("Starting Task 2...")
Await CustomWaitAsync(2000)
Console.WriteLine("Task 2 completed.")
End Function
Private Shared Async Function CustomWaitAsync(ByVal milliseconds As Integer) As Task
Await Task.Run(Sub() Thread.Sleep(milliseconds)) ' Run in a separate task to avoid blocking the main thread
End Function
End Class在这里,int参数,代表延迟时间(以毫秒计)。 该方法使用异步委托在新任务中运行Thread.Sleep函数,确保当前任务状态在等待时被阻塞,而主线程不受影响。
选择合适的等待策略
现在我们已经介绍了C#的等待语句、休眠命令、异步方法、计时器和自定义等待函数,了解什么时候使用每种技术是非常重要的。 这里是一个快速总结:
- 当您需要一种简单的方法来暂停代码执行指定时间时,使用
Thread.Sleep功能。 - 当您需要同时执行多个任务且不阻塞主线程时,请使用异步方法和任务。
- 当您需要在指定的时间间隔执行特定任务时,请使用计时器。
- 当内置方法无法满足您的特定要求时,请创建自定义等待函数。
使用IronPDF和等待功能生成PDF
IronPDF是一个为网络开发人员特别设计的轻量级.NET PDF库。 它使读取、编写和操作PDF文件变得轻松,可以将各种文件类型转换为PDF内容,您可以在桌面和网络的.NET项目中使用它。 最佳部分 - 在开发环境中免费试用。 让我们深入了解。
IronPDF可与HTML文件、URL、原始字符串和ZIP文件一起使用。 以下是代码的快速概述:
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 ClassIronPDF可以无缝集成您的等待策略,在执行任务后、安排的时间间隔内或当前线程恢复执行时生成PDF文档。
例如,您可以与异步方法结合使用IronPDF,在从数据库获取数据后生成PDF报告而不阻塞主线程。 同样,您可以使用计时器类在常规时间间隔内创建应用程序数据的PDF快照。
安装IronPDF库
IronPDF易于使用,但安装起来甚至更简单。 您可以这样做的方式有几种:
方法1:NuGet包管理器控制台
在Visual Studio中,在解决方案资源管理器中右键单击References,然后单击Manage NuGet Packages。 单击浏览并搜索'IronPDF',然后安装最新版本。 如果您看到这样,它就运行了:

您还可以转到Tools -> NuGet Package Manager -> Package Manager Console,并在Package Manager Tab中输入以下行:
最后,您可以从NuGet的官方网站直接获取IronPDF。 从页面右侧菜单中选择Download Package选项,双击下载以自动安装,然后重新加载解决方案以在项目中开始使用它。
不起作用? 您可以在我们的高级NuGet安装页面上找到特定平台的帮助。
方法2:使用DLL文件
您还可以直接从我们这里获取IronPDF DLL文件并手动将其添加到Visual Studio。 有关完整说明及Windows、MacOS和Linux DLL包的链接,请查看我们的专门安装页面。
如何在IronPDF中使用C# Wait
您可以在以下示例中看到如何在IronPDF中包含等待功能:
using System;
using System.Threading.Tasks;
using System.Diagnostics;
using IronPdf;
class Program
{
public static async Task Main()
{
Console.WriteLine("Starting the PDF generation task...");
Stopwatch stopwatch = Stopwatch.StartNew();
await Task.Delay(3000); // Wait for 3 seconds
GeneratePdf();
Console.WriteLine("PDF generated successfully.");
}
private static void GeneratePdf()
{
var htmlToPdf = new ChromePdfRenderer();
var pdf = htmlToPdf.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
pdf.SaveAs("HelloWorld.pdf");
}
}Imports System
Imports System.Threading.Tasks
Imports System.Diagnostics
Imports IronPdf
Friend Class Program
Public Shared Async Function Main() As Task
Console.WriteLine("Starting the PDF generation task...")
Dim stopwatch As Stopwatch = System.Diagnostics.Stopwatch.StartNew()
Await Task.Delay(3000) ' Wait for 3 seconds
GeneratePdf()
Console.WriteLine("PDF generated successfully.")
End Function
Private Shared Sub GeneratePdf()
Dim htmlToPdf = New ChromePdfRenderer()
Dim pdf = htmlToPdf.RenderHtmlAsPdf("<h1>Hello, World!</h1>")
pdf.SaveAs("HelloWorld.pdf")
End Sub
End Class在这里,我们使用Task.Delay方法等待3秒钟,然后生成PDF。 然后,该PDF将在等待完成后作为"HelloWorld.pdf"保存在应用程序的工作目录中。
以下是最终产品:

在IronPDF中使用Wait方法
在C#应用程序中,您可以有效地使用sleep功能来管理当前线程和CPU时间,同时执行诸如加载数据到DataTable或使用IronPDF生成PDF报告等操作。
结论
开始时可能显得不合常理,但在构建高效应用程序时,将等待语句加入您的代码中是必不可少的技能。 通过集成IronPDF,您可以将您的应用程序提升到一个新的水平,实时创建PDF文档而不阻塞主线程。
准备好亲自体验IronPDF了吗? 您可以从我们的30天免费试用开始。 它也完全免费用于开发目的,因此您可以真正了解它的功能。 如果您喜欢所见,IronPDF起价仅需$999。 为了获得更大的折扣,请查看Iron Suite,您可以以两种价格获取Iron Software全部九种工具。 祝您编码愉快!

Jacob Mellor 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。
相关文章


