跳至頁尾內容
開發者更新

C# 計時器(對於開發者的運行原理)

C# 中的計時器類別是強大的工具,用於安排在指定的間隔內執行程式碼。 無論您是在開發 Windows Form 應用程式還是控制台應用程式,了解如何使用計時器都能大大提升您應用程式的功能。 本教程將引導您了解在 C# 中使用計時器的基礎知識,包括如何設置計時器、處理事件以及確保它們在應用程式中順利運行。 我們還將討論如何使用IronPDF 用於 C# 應用程式中的自動化 PDF 生成來自動化 C# 中使用計時器的 PDF 生成過程。

Introduction to Timer Classes in C

C# 計時器 (開發人員如何使用):圖 1 - 計時器類別

C# 提供多個計時器類別,每個類別適用於不同的任務和環境。 最常用的計時器類別是用於伺服器的 System.Timers.Timer 和用於 Windows Forms 應用程式的 System.Windows.Forms.Timer。 當使用計時器類別時,了解事件處理程式的作用至關重要,因為這些處理程式規定了計時器在每個重要時刻執行的操作,例如滴答(tick)或經過(elapsed)事件時間間隔。

設置新計時器

配置計時器的時間間隔是其操作的基礎,決定了計時器的事件處理程式的調用頻率,從而控制應用程式的時間敏感功能的節奏。 要在您的 C# 應用程式中使用計時器,尤其是在開發 Windows Forms 應用程式時,您可以從工具箱中將 System.Windows.Forms.Timer 元件新增到表單上,或者以程式化方式建立計時器物件以獲得更多靈活性。

var timer = new System.Timers.Timer(); // Create a new timer
timer.Interval = 2000; // Sets the timer interval to tick every 2 seconds
var timer = new System.Timers.Timer(); // Create a new timer
timer.Interval = 2000; // Sets the timer interval to tick every 2 seconds
Dim timer = New System.Timers.Timer() ' Create a new timer
timer.Interval = 2000 ' Sets the timer interval to tick every 2 seconds
$vbLabelText   $csharpLabel

這個簡單的設置建立了一個每 2 秒滴答一次的計時器。 然而,要讓計時器執行動作,您需要將其連接到事件處理程式。

處理經過事件

通過將經過事件處理程式附加到 System.Timers.TimerElapsed 事件,您可以確保應用程式能夠在每個間隔執行任務,有效地響應基於時間的觸發。 每次計時器的間隔結束時,該事件被觸發。 您將事件處理程式附加到此事件以指定計時器滴答時應發生的事情:

timer.Elapsed += OnTimedEvent;
timer.Elapsed += OnTimedEvent;
timer.Elapsed += OnTimedEvent
$vbLabelText   $csharpLabel

在上述程式碼中,OnTimedEvent 是您定義的方法,每當計時器的 Elapsed 事件被觸發時都會調用此方法。

建立事件處理程式

在定義計時器事件處理程式時,您編寫一個方法以響應計時器的滴答事件執行,允許對在預定時間間隔執行的操作進行精確控制。 計時器的 Elapsed 事件的事件處理程式通常是這樣的:

static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
    Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}", e.SignalTime);
}
static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
    Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}", e.SignalTime);
}
Shared Sub OnTimedEvent(ByVal source As Object, ByVal e As System.Timers.ElapsedEventArgs)
	Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}", e.SignalTime)
End Sub
$vbLabelText   $csharpLabel

此方法僅在計時器結束時將當前時間列印到控制台,演示了如何響應計時器事件。

啟動和停止計時器

設置計時器和其事件處理程式後,您需要啟動計時器。 您可以通過將其 Enabled 屬性設置為 true 或調用 Start 方法來實現這一操作:

timer.Enabled = true; // or timer.Start();
timer.Enabled = true; // or timer.Start();
timer.Enabled = True ' or timer.Start();
$vbLabelText   $csharpLabel

要停止計時器,您可以將 Enabled 設置為 false 或調用 Stop 方法。 這對於防止應用程式在不需要運行無用操作時非常重要。

在 Windows Forms 應用程式中使用計時器

System.Windows.Forms.Timer 是一個有價值的 Windows Forms 元件,設計上與 Windows Forms 應用程式的事件驅動模型無縫整合,使得定期執行操作而不影響使用者介面的響應性。

範例:向表單新增計時器

在 Windows Forms 應用程式中,您可以從工具箱中將計時器控制項拖到表單上,或以程式化方式建立它,如下所示:

System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
myTimer.Interval = 1000; // 1 second interval
myTimer.Tick += new EventHandler(TimerEventProcessor);
myTimer.Start();
System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
myTimer.Interval = 1000; // 1 second interval
myTimer.Tick += new EventHandler(TimerEventProcessor);
myTimer.Start();
Dim myTimer As New System.Windows.Forms.Timer()
myTimer.Interval = 1000 ' 1 second interval
AddHandler myTimer.Tick, AddressOf TimerEventProcessor
myTimer.Start()
$vbLabelText   $csharpLabel

這裡,TimerEventProcessor 是一個事件處理程式,當每次 Tick 事件發生時都會被調用,類似於 System.Timers.Timer 中的 Elapsed 事件。

高級計時器管理

計時器的執行緒安全

在使用計時器時,了解應用程式的執行緒模型至關重要。 System.Timers.TimerSystem.Threading.Timer 在執行緒池執行緒上執行它們的回調,允許並行執行。 但是,如果你的回調方法修改共用資料或與使用者介面元素互動,這可能會導致執行緒安全問題。 要從計時器的回調中安全地更新 UI 元素,您必須使用特定於您應用程式型別的技術將呼叫調回 UI 執行緒(例如,在 Windows Forms 中使用 InvokeBeginInvoke)。

高精度計時

對於需要高精度計時的應用程式(例如,多媒體應用程式或遊戲),System.Diagnostics.Stopwatch 類可能比計時器更適合用來測量經過時間的高精度。 雖然本身不是計時器,但 Stopwatch 類可以與計時器一起使用,以實現精確的時間測量。

實際範例

範例:實現倒數計時器

計時器實用的一個常見場景是建立倒數計時器。 這可以通過將計時器間隔設置為一秒(1000 毫秒),並在每次計時器結束時減少計數器來完成。 當計數器達到零時,計時器停止,表示倒計時結束。

using System;

namespace CountdownApp
{
    class Program
    {
        static int countdownTime = 10; // Countdown from 10 seconds

        public static void Main(string[] args) // Main method
        {
            StartCountdown();
            Console.ReadLine(); // Prevent console from closing immediately
        }

        static void StartCountdown()
        {
            var timer = new System.Timers.Timer(1000); // Tick every second
            timer.Elapsed += UpdateCountdown;
            timer.Enabled = true;
        }

        static void UpdateCountdown(Object source, System.Timers.ElapsedEventArgs e)
        {
            if (countdownTime > 0)
            {
                Console.WriteLine(countdownTime-- + " seconds remaining");
            }
            else
            {
                Console.WriteLine("Countdown finished!");
                ((System.Timers.Timer)source).Stop(); // Stop the timer
            }
        }
    }
}
using System;

namespace CountdownApp
{
    class Program
    {
        static int countdownTime = 10; // Countdown from 10 seconds

        public static void Main(string[] args) // Main method
        {
            StartCountdown();
            Console.ReadLine(); // Prevent console from closing immediately
        }

        static void StartCountdown()
        {
            var timer = new System.Timers.Timer(1000); // Tick every second
            timer.Elapsed += UpdateCountdown;
            timer.Enabled = true;
        }

        static void UpdateCountdown(Object source, System.Timers.ElapsedEventArgs e)
        {
            if (countdownTime > 0)
            {
                Console.WriteLine(countdownTime-- + " seconds remaining");
            }
            else
            {
                Console.WriteLine("Countdown finished!");
                ((System.Timers.Timer)source).Stop(); // Stop the timer
            }
        }
    }
}
Imports System

Namespace CountdownApp
	Friend Class Program
		Private Shared countdownTime As Integer = 10 ' Countdown from 10 seconds

		Public Shared Sub Main(ByVal args() As String) ' Main method
			StartCountdown()
			Console.ReadLine() ' Prevent console from closing immediately
		End Sub

		Private Shared Sub StartCountdown()
			Dim timer = New System.Timers.Timer(1000) ' Tick every second
			AddHandler timer.Elapsed, AddressOf UpdateCountdown
			timer.Enabled = True
		End Sub

		Private Shared Sub UpdateCountdown(ByVal source As Object, ByVal e As System.Timers.ElapsedEventArgs)
			If countdownTime > 0 Then
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Console.WriteLine(countdownTime-- + " seconds remaining");
				Console.WriteLine(countdownTime & " seconds remaining")
				countdownTime -= 1
			Else
				Console.WriteLine("Countdown finished!")
				DirectCast(source, System.Timers.Timer).Stop() ' Stop the timer
			End If
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

這是上面程式碼的輸出:

C# 計時器 (開發人員如何使用):圖 2 - 倒數計時器輸出

範例:常規資料庫檢查排程

計時器可用於經常性地檢查資料庫,例如查詢新資料或清理舊紀錄。 此範例設置一個每小時查詢一次資料庫的計時器:

private static void SetupDatabaseCheckTimer()
{
    var timer = new System.Timers.Timer(3600000); // Set to 1 hour
    timer.Elapsed += CheckDatabase;
    timer.Enabled = true;
}

private static void CheckDatabase(Object source, System.Timers.ElapsedEventArgs e)
{
    // Perform database operations here
    Console.WriteLine("Database checked at " + e.SignalTime);
}
private static void SetupDatabaseCheckTimer()
{
    var timer = new System.Timers.Timer(3600000); // Set to 1 hour
    timer.Elapsed += CheckDatabase;
    timer.Enabled = true;
}

private static void CheckDatabase(Object source, System.Timers.ElapsedEventArgs e)
{
    // Perform database operations here
    Console.WriteLine("Database checked at " + e.SignalTime);
}
Private Shared Sub SetupDatabaseCheckTimer()
	Dim timer = New System.Timers.Timer(3600000) ' Set to 1 hour
	AddHandler timer.Elapsed, AddressOf CheckDatabase
	timer.Enabled = True
End Sub

Private Shared Sub CheckDatabase(ByVal source As Object, ByVal e As System.Timers.ElapsedEventArgs)
	' Perform database operations here
	Console.WriteLine("Database checked at " & e.SignalTime)
End Sub
$vbLabelText   $csharpLabel

IronPDF簡介

IronPDF - 輕鬆從 HTML 和 ASPX 生成 PDF 特別因其易於將 HTML 或 URL 生成 PDF 而受到讚賞,基本上允許您的應用程式"列印"任何HTML 內容作為 PDF 文件。 這對於生成報告、發票或任何需要以標準格式呈現的網頁內容特別有用。 IronPDF 還支持高級功能,如 CSS 樣式、JavaScript 和自定義字型,確保生成的 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
$vbLabelText   $csharpLabel

安裝IronPDF

您可以使用 NuGet 套件管理器執行以下命令安裝 IronPDF:

Install-Package IronPdf

範例

想像一下,您需要生成一個每日報告,以 PDF 格式顯示每天更新的資料。 為簡化起見,我們將生成一個基本的 HTML 報告,並每 24 小時使用 IronPDF 將其轉換為 PDF。 在您的 C# 應用程式中,您將設置一個 System.Timers.Timer 每 24 小時觸發一次。 請注意,間隔是以毫秒為單位設置的,所以 24 小時表示為 24 * 60 * 60 * 1000 毫秒。

using System;
using System.Timers;
using IronPdf;
using Timer = System.Timers.Timer;

class Program
{
    static void Main(string[] args)
    {
        // Set up the timer for 24 hours
        Timer timer = new Timer(24 * 60 * 60 * 1000);
        timer.Elapsed += OnTimedEvent;
        timer.AutoReset = true;
        timer.Enabled = true;

        Console.WriteLine("Press Enter to exit the program.");
        Console.ReadLine();
    }

    private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        GeneratePdfReport();
    }

    private static void GeneratePdfReport()
    {
        var renderer = new HtmlToPdf();
        var pdf = renderer.RenderHtmlAsPdf("<h1>Daily Report</h1><p>This is the automated daily report.</p>");
        string outputPath = $"f:\\DailyReport_{DateTime.Now:yyyyMMdd}.pdf";
        pdf.SaveAs(outputPath);
        Console.WriteLine($"Generated PDF report at {outputPath}");
    }
}
using System;
using System.Timers;
using IronPdf;
using Timer = System.Timers.Timer;

class Program
{
    static void Main(string[] args)
    {
        // Set up the timer for 24 hours
        Timer timer = new Timer(24 * 60 * 60 * 1000);
        timer.Elapsed += OnTimedEvent;
        timer.AutoReset = true;
        timer.Enabled = true;

        Console.WriteLine("Press Enter to exit the program.");
        Console.ReadLine();
    }

    private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        GeneratePdfReport();
    }

    private static void GeneratePdfReport()
    {
        var renderer = new HtmlToPdf();
        var pdf = renderer.RenderHtmlAsPdf("<h1>Daily Report</h1><p>This is the automated daily report.</p>");
        string outputPath = $"f:\\DailyReport_{DateTime.Now:yyyyMMdd}.pdf";
        pdf.SaveAs(outputPath);
        Console.WriteLine($"Generated PDF report at {outputPath}");
    }
}
Imports System
Imports System.Timers
Imports IronPdf
Imports Timer = System.Timers.Timer

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Set up the timer for 24 hours
		Dim timer As New Timer(24 * 60 * 60 * 1000)
		AddHandler timer.Elapsed, AddressOf OnTimedEvent
		timer.AutoReset = True
		timer.Enabled = True

		Console.WriteLine("Press Enter to exit the program.")
		Console.ReadLine()
	End Sub

	Private Shared Sub OnTimedEvent(ByVal source As Object, ByVal e As ElapsedEventArgs)
		GeneratePdfReport()
	End Sub

	Private Shared Sub GeneratePdfReport()
		Dim renderer = New HtmlToPdf()
		Dim pdf = renderer.RenderHtmlAsPdf("<h1>Daily Report</h1><p>This is the automated daily report.</p>")
		Dim outputPath As String = $"f:\DailyReport_{DateTime.Now:yyyyMMdd}.pdf"
		pdf.SaveAs(outputPath)
		Console.WriteLine($"Generated PDF report at {outputPath}")
	End Sub
End Class
$vbLabelText   $csharpLabel

輸出

一旦您運行程式碼,它將在控制台中顯示以下輸出。 在這裡,我修改了程式碼以便快速輸出,因此我使用了一個 10 秒的計時器。

C# 計時器 (開發人員如何使用):圖 3 - 控制台輸出

這是生成的 PDF:

C# 計時器 (開發人員如何使用):圖 4 - PDF 報告

結論

C# 計時器 (開發人員如何使用):圖 5 - 授權

總之,將 C# 計時器與 IronPDF 結合使用提供了一種強大的方法,用於在 .NET 應用程式中自動生成和管理 PDF 文件。 通過提供的範例,我們探討了如何設置 C# 計時器以在固定的時間間隔觸發 PDF 生成任務,無論是用於頻繁的測試目的還是排程的報告生成。 using C# 計時器,我們可以精確地控制 PDF 相關任務的執行時間,允許定期更新、報告生成或任何需按計劃發生的任務。 IronPDF 增強了這種能力,提供一種簡單高效的方法來建立、操控和保存基於動態內容、HTML 或甚至是網頁的 PDF 文件。

IronPDF 提供免費試用版和授權資訊,有完整存取和支援的授權可以購買。 這提供了一種經濟有效的方式來在您的 .NET 應用程式中實現全面的 PDF 功能。

常見問題

C#中提供的主要計時器類有哪些?

C#提供多個計時器類,包括用於伺服器基礎應用的System.Timers.Timer和用於Windows Forms應用的System.Windows.Forms.Timer,它們各自用於不同的執行緒和執行需求。

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

您可以通過使用IronPDF的RenderHtmlAsPdf方法在C#中將HTML轉換為PDF,此方法支持高級功能如CSS和JavaScript,非常適合生成報告和發票。

如何在C#應用中設置和管理計時器?

要在C#應用中設置計時器,請建立一個計時器類的實例,指定其間隔,並將事件處理器附加到其ElapsedTick事件,以便允許您定期執行程式碼。

在C#應用中使用計時器的好處是什麼?

C#中的計時器有助於自動化任務,如定期排程資料庫檢查,實施倒計時器,並觸發自動化過程如PDF生成。

IronPDF如何在C#中自動化PDF生成?

IronPDF可以通過使用C#計時器於預定的時間間隔觸發PDF生成過程,實現每天報告或發票的生成。

如何處理System.Timers.Timer的執行緒問題?

System.Timers.Timer在執行緒池執行緒上執行回調,這可能導致執行緒安全問題。妥善管理涉及到確保UI更新透過使用如InvokeBeginInvoke的技術返回到UI執行緒。

如何從計時器的事件中更新C#的UI元件?

要從計時器的事件中更新C#的UI元件,您必須將調用重新分派給UI執行緒,通常在Windows Forms應用中使用InvokeBeginInvoke方法。

計時器如何增強C#應用中的功能?

計時器可通過允許在特定時間間隔排程任務來增強功能,透過自動化提高應用的效率和回應能力。

如何在C#專案中安裝和使用IronPDF?

IronPDF可以透過NuGet包管理器使用命令Install-Package IronPdf在C#專案中安裝。安裝後,您可以使用其方法將HTML轉換為PDF並自動化PDF的生成。

哪些實例證明了C#中計時器的使用?

C#中計時器的實際例子包括實施倒計時器、排程定期資料庫更新,以及使用IronPDF自動化每天的PDF報告生成。

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

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

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