跳過到頁腳內容
.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");
    }
}
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
$vbLabelText   $csharpLabel

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

同步方法和任務

C# 中的 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);
   }
}
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
$vbLabelText   $csharpLabel

在上述範例中,我們建立了一個間隔為 1 秒的計時器。 OnTimerElapsed 方法會在計時器每次滴答作響時執行。 我們將 AutoReset 屬性設為 true,以便計時器在每次滴答後自動重新啟動。 將 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 參數,表示以毫秒為單位的延遲時間。 此方法使用非同步委託在新任務中執行 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 方法等待 3 秒後再產生 PDF。 等待完成後,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 的起價低至$999 。 若想節省更多的費用,請參閱 Iron Suite,您可以兩個工具的價格獲得全部九個 Iron Software 工具。 祝您編碼愉快!

Csharp Wait For Seconds 3 related to 結論

常見問題解答

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

在 C# 中,您可以使用 `Thread.Sleep` 方法來同步等待,或使用 `Task.Delay` 來進行異步等待。這些方法允許您暫停代碼執行指定時間,確保任務在正確的時間執行。

C# 中的 WaitFor 類別是什麼?

C# 中的 WaitFor 類別用於在代碼中實現各種等待策略。它提供了像 `Thread.Sleep` 和 `Task.Delay` 這樣的方法來幫助管理任務執行時間,使開發人員能夠根據需要暫停代碼執行。

如何在 C# 中實現 PDF 任務的異步等待?

在 C# 中可以使用 `Task.Delay` 方法來實現異步等待,這樣可以在不阻塞主執行緒的情況下進行等待。這對於 PDF 任務尤為有用,以確保平滑的執行和適當的任務調度。

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

計時器,如 `System.Timers.Timer` 類別提供的那些,允許您在特定間隔預定任務。它們在需定期執行任務(如 PDF 生成)時非常有用,確保高效的任務管理,而不會阻塞主執行緒。

可以在 C# 中創建自定義等待函數嗎?

是的,您可以使用異步委託在 C# 中創建自定義等待函數。這樣可以滿足特定需求的代碼執行暫停,特別是在預設的等待方法不夠時。

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

您可以透過使用異步方法和計時器在 C# 中將 PDF 生成與等待策略整合。這確保 PDF 創建任務得以高效管理,允許時間表安排的執行而不擋住其他進程。

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

在 C# 中要將 HTML 轉換為 PDF,您可以使用像 IronPDF 這樣的庫。此庫提供將 HTML 字符串、URL 和文件高效轉換為 PDF 文件的方法。

使用 C# 中的異步方法有什麼好處?

C# 中的異步方法提供並發任務執行的好處,通過允許多個任務並行執行而不阻塞主執行緒來提高應用程式效率。

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

要在 .NET 專案中安裝 PDF 庫,您可以使用 Visual Studio 中的 NuGet 包管理器來搜索並安裝該庫。或者,您也可以下載該庫的 DLL 文件並手動添加到項目中。

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

是的,您可以在 C# 中使用 `Thread.Sleep` 方法來進行同步暫停,或使用 `Task.Delay` 方法來進行異步暫停,這樣可以控制 PDF 生成任務的時機。

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

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

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

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我