跳過到頁腳內容
.NET幫助

C# 等待數秒(開發者的工作原理)

在程式設計中,有時您會想要暫停或延遲執行程式碼一段時間。這樣您就可以模擬不同的時間條件、優先處理某些任務、在不阻礙主線程的情況下執行其他任務等等。

在本指南中,我們將解釋如何在 C# 中等待,包括 async 方法、睡眠命令、睡眠函數、控制台應用程式,以及如何在我們業界領先的 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");
    }
}
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");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

在此,程式會先在控制台列印"Starting the program...",然後再使用 Thread.Sleep 方法暫停 3,000 毫秒(或三秒鐘)。 在指定的延遲時間之後,程式會恢復並在控制台列印輸出"...程式在 3 秒之後繼續"。

同步方法和任務

C# 中的 Async 方法可讓您在不干擾主線程下,同時執行多個任務。 這表示當一個任務在等待時,其他任務可以繼續執行。 要實作一個 async 方法,您需要使用 async 關鍵字和 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");
   }
}
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
$vbLabelText   $csharpLabel

在這個程式碼範例中,我們有兩個任務同時執行。DoSomethingAsync 方法接收一個 int 參數,該參數代表任務應延遲的時間(以毫秒為單位)(正如您在程式碼中看到的 30002000 所示,都是一個逾時值)。 Task.Delay 方法類似於 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);
   }
}
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);
   }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

在上述範例中,我們建立了一個間隔為 1 秒的計時器。 OnTimerElapsed 方法會在計時器每次滴答作響時執行。 我們將 AutoReset 屬性設定為 true,以便計時器在每次 tick 後自動重新啟動。 Enabled 屬性設定為 true 即可啟動計時器。

當您執行此控制台應用程式時,您會看到計時器每秒滴答一次,並將滴答時間列印到控制台。 程式會持續執行,直到您按下任何鍵退出為止。

建立自訂等待函數

有時候,您可能需要自訂等待函式來滿足程式碼中的特定需求。 例如,您可能想要建立一個等待函數,僅阻塞目前的任務,而不是整個線程。 您可以使用 async delegates 來實現這一目標。

以下是自訂等待函數的範例:

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
   }
}
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
$vbLabelText   $csharpLabel

在這裡,CustomWaitAsync 方法接受一個 int 參數,代表以毫秒為單位的延遲時間。 該方法使用 a async delegate 在新任務中執行 Thread.Sleep 函式,確保在等待時會阻塞目前的任務狀態,但不會阻塞主線程。

選擇正確的等待策略

現在我們已經介紹了 C# 的 wait 語句、sleep 指令、async 方法、計時器和自訂 wait 函數,知道何時使用每種技術是非常重要的。 以下是快速摘要:

  • 當您需要一個簡單的方法來暫停程式碼執行一段指定的時間時,請使用 Thread.Sleep 函式。
  • 當您需要同時執行多個任務而不阻塞主線程時,請使用 async 方法和任務。
  • 當您需要在指定時間間隔執行特定任務時,請使用計時器。
  • 當您有內建方法無法滿足的特定需求時,請建立自訂的等待函式。

使用 Wait 功能用 IronPDF 生成 PDF。

IronPDF 是專為 Web 開發人員設計的輕量級 .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");
   }
}
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

IronPDF 可與您的等待策略無縫整合,在執行任務後、排程間隔中或當前線程恢復執行時生成 PDF 文件。

例如,您可以將 IronPDF 與 async 方法結合使用,在從資料庫取得資料後生成 PDF 報告,而不會阻塞主線程。 同樣地,您也可以使用計時器類別來定期建立應用程式資料的 PDF 快照。

安裝 IronPdf 函式庫

IronPDF 易於使用,但安裝更容易。 有幾種方法可以做到這一點:

方法 1:NuGet 套件管理員控制台

在 Visual Studio 中,在 Solution Explorer 中,右鍵按一下 References,然後按一下 Manage NuGet Packages。 點擊瀏覽並搜尋"IronPDF",安裝最新版本。 如果您看到這個,它就成功了:

Csharp Wait For Seconds 1 related to 方法 1:NuGet 套件管理員控制台

您也可以前往 Tools -> NuGet Package Manager -> Package Manager Console,然後在 Package Manager Tab 中輸入以下一行:

Install-Package IronPdf

最後,您可以直接從 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");
   }
}
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
$vbLabelText   $csharpLabel

在此,我們使用 Task.Delay 方法在產生 PDF 之前等待 3 秒。 等待完成後,PDF 會以"HelloWorld.pdf"的形式儲存於應用程式的工作目錄中。

以下是最終產品:

Csharp Wait For Seconds 2 related to 如何在 IronPDF 中使用 C# Wait。

使用 IronPDF 的等待方法。

在 C# 應用程式中,您可以有效地使用 sleep 函數來管理目前的線程及 CPU 時間,同時執行一些作業,例如將資料載入 DataTable 或使用 IronPDF 產生 PDF 報表。

結論

起初看起來可能有違直覺,但在程式碼中執行等待語句是建立高效應用程式時必須具備的技能。 透過結合 IronPDF,您可以在不阻塞主線程的情況下,即時建立 PDF 文件,讓您的應用程式更上一層樓。

準備好使用 IronPdf 了嗎? 您可以從我們的 30天免費試用開始。 它還可以完全免費用於開發目的,讓您真正能一窺其真面目。 如果您喜歡您所看到的,IronPDF 的起價低至 $799。 若想節省更多的費用,請參閱 Iron Suite,您可以兩個工具的價格獲得全部九個 Iron Software 工具。 祝您編碼愉快!

Csharp Wait For Seconds 3 related to 結論

常見問題解答

如何延遲 C# 中的 PDF 渲染?

您可以使用同步等待的 `Thread.Sleep` 方法或非同步等待的 `Task.Delay` 方法延遲 C# 中的 PDF 渲染。這些方法可讓您在指定的時間內暫停執行程式碼,確保在正確的時間執行任務。

C# 中的 WaitFor 類是什麼?

C# 中的 WaitFor 類用於在程式碼中實作各種等待策略。它提供了 `Thread.Sleep` 和 `Task.Delay` 等方法來協助管理任務的執行時序,讓開發人員可以在需要時暫停程式碼的執行。

如何在 C# 中為 PDF 任務實現 async 等待?

C# 中的異步等待可以使用`Task.Delay`方法來實現,它允許您在不阻塞主線程的情況下進行異步等待。這在 PDF 任務中尤其有用,可確保順利執行和適當的任務排程。

計時器在 C# 中管理任務執行時扮演什麼角色?

計時器,例如由 `System.Timers.Timer` 類提供的計時器,可讓您以特定的間隔來排程任務。它們對於定期執行 PDF 產生等任務非常有用,可確保有效率的任務管理而不會阻塞主線程。

您可以在 C# 中建立自訂的等待函數嗎?

是的,您可以使用 async delegates 在 C# 中建立自訂的等待函數。這允許量身訂做的程式碼執行暫停以滿足特定需求,尤其是當預設的等待方法無法滿足需求時。

如何在 C# 中整合 PDF 生成與等待策略?

您可以在 C# 中使用 async 方法和計時器,將 PDF 生成與等待策略整合在一起。這可確保有效管理 PDF 建立任務,允許排程執行而不會阻塞其他程序。

如何在 C# 中將 HTML 轉換為 PDF?

要在 C# 中將 HTML 轉換為 PDF,您可以使用 IronPDF 之類的函式庫。這個函式庫提供將 HTML 字串、URL 和檔案有效轉換為 PDF 文件的方法。

在 C# 中使用 async 方法有什麼好處?

C# 中的 Async 方法提供了並發任務執行的優點,它允許多個任務並行執行而不會阻塞主線程,從而提高了應用程式的效率。

如何在 .NET 專案中安裝 PDF 函式庫?

若要在 .NET 專案中安裝 PDF 函式庫,您可以使用 Visual Studio 中的 NuGet Package Manager 搜尋並安裝函式庫。另外,您也可以下載函式庫的 DLL 檔案,並將其手動新增至專案中。

是否可以在 C# 中暫停 PDF 渲染特定時間?

是的,您可以使用 C# 中的方法,例如同步暫停的 `Thread.Sleep` 或非同步暫停的 `Task.Delay`,將 PDF 渲染暫停一段特定時間,讓您可以控制 PDF 生成任務的時間。

Jacob Mellor, Team Iron 首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。