.NETヘルプ C# Event Handler(開発者向けの仕組み) Curtis Chau 更新日:8月 5, 2025 Download IronPDF NuGet Download テキストの検索と置換 テキストと画像のスタンプ Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 最新の.NETアプリケーションでは、イベント駆動型プログラミングが応答性を改善し、スムーズなユーザーエクスペリエンスを保証する重要な役割を果たします。 PDF生成のようなタスクが時間を要する場合、メインスレッドをブロックしたくないです。 代わりにイベントハンドラーを使用して非同期でタスクを実行し、イベントが発生したらリアクトすることで、アプリケーションをよりインタラクティブで応答性の高いものにできます。 このガイドでは、デスクトップおよびウェブ環境でシームレスなPDFワークフローを実現するために、IronPDFをC#のイベント処理メソッドと統合する方法を紹介します。 WinForms、WPF、または他のC#プログラミング言語ベースのプラットフォームを使用しているかどうかにかかわらず、このガイドはあなたをサポートします。 IronPDFプロジェクトのセットアップ イベント処理に入る前に、.NETプロジェクトでIronPDFをすばやくセットアップしましょう。 NuGetを介してIronPDFをインストールする Visual Studioのパッケージマネージャーコンソールで次を実行します: Install-Package IronPdf これにより、IronPDFを使用してPDFを生成するために必要なすべてがインストールされます。 IronPDFを使用した基本的なPDF生成 IronPDFが動作していることを確認するための簡単な例です: using IronPdf; var renderer = new ChromePdfRenderer(); var pdf = renderer.RenderHtmlAsPdf("<h1>Hello from IronPDF!</h1>"); pdf.SaveAs("example.pdf"); using IronPdf; var renderer = new ChromePdfRenderer(); var pdf = renderer.RenderHtmlAsPdf("<h1>Hello from IronPDF!</h1>"); pdf.SaveAs("example.pdf"); Imports IronPdf Private renderer = New ChromePdfRenderer() Private pdf = renderer.RenderHtmlAsPdf("<h1>Hello from IronPDF!</h1>") pdf.SaveAs("example.pdf") $vbLabelText $csharpLabel これが動作したら、イベントフィールドを追加し、登録されたデリゲートを結びつけ、デリゲートタイプを使用してイベント駆動型ワークフローを作成する準備が整いました。 .NET開発者のためのC#イベントハンドラの基礎 イベント駆動型プログラミングの基本 イベント駆動型プログラミングでは、PDFの生成が完了した場合など、イベントが発生したときにアプリが応答します。 C#は型安全な関数ポインターとしてデリゲートを使用することで、アプリがどのように反応するべきかを定義できます。 通常はeventキーワードを使用してイベントを宣言し、イベント処理メソッドに接続して、カスタムEventArgsサブクラスを使用してデータを渡します。 eventキーワードを使用してイベントを宣言する C#はeventキーワードを使用してイベントメンバーを宣言します。 例えば: public event EventHandler PdfGenerated; public event EventHandler PdfGenerated; Public Event PdfGenerated As EventHandler $vbLabelText $csharpLabel この行は、PdfGeneratedという名前のイベントフィールドを宣言します。 EventHandlerを使用し、次のパラメータリストを持つ組み込みデリゲートです: (object sender, EventArgs e)—これが.NETでのイベントの命名パターンと呼ばれることがよくあります。 C#でのイベントの定義と購読 デリゲートを使用してイベントにメソッドを追加する C#イベントは、+=構文を使用してランタイムで<強調>メソッドを追加する</強調>ことをサポートします。 1. Visual Studioを開き、「ツール」>「NuGetパッケージマネージャー」>「ソリューションのNuGetパッケージの管理」に移動します。 pdfService.PdfGenerated += (s, e) => { Console.WriteLine("PDF was generated!"); }; pdfService.PdfGenerated += (s, e) => { Console.WriteLine("PDF was generated!"); }; AddHandler pdfService.PdfGenerated, Sub(s, e) Console.WriteLine("PDF was generated!") End Sub $vbLabelText $csharpLabel この購読者クラスは、PdfGeneratedイベントをリッスンし、トリガーされるとメソッドを呼び出します。 カスタムイベントデータ 生成されたファイルパスなどのイベントデータを渡すには、EventArgsから派生したクラスを定義します: public class PdfGeneratedEventArgs : EventArgs { public string FilePath { get; set; } // returned value } public class PdfGeneratedEventArgs : EventArgs { public string FilePath { get; set; } // returned value } Public Class PdfGeneratedEventArgs Inherits EventArgs Public Property FilePath() As String ' - returned value End Class $vbLabelText $csharpLabel 次に、ジェネリックなデリゲートタイプを使用してイベントを再定義します: public event EventHandler<PdfGeneratedEventArgs> PdfGenerated; public event EventHandler<PdfGeneratedEventArgs> PdfGenerated; Public Event PdfGenerated As EventHandler(Of PdfGeneratedEventArgs) $vbLabelText $csharpLabel イベントが発生するとき、構造化された型安全なデータを提供し、応答ロジックをより強力にすることができます。 複数のイベントを処理する 複数のイベントを定義できます: public event EventHandler PdfGenerationStarted; public event EventHandler<PdfGeneratedEventArgs> PdfGenerationCompleted; public event EventHandler PdfGenerationStarted; public event EventHandler<PdfGeneratedEventArgs> PdfGenerationCompleted; Public Event PdfGenerationStarted As EventHandler Public Event PdfGenerationCompleted As EventHandler(Of PdfGeneratedEventArgs) $vbLabelText $csharpLabel 各イベントフィールドは購読者クラスによって処理され、段階ごとに異なるイベントハンドラーメソッドを許可します。 この懸念の分離は、複雑なワークフローで理にかなっています。 IronPDFを使用したイベントハンドラー 大型のPDFを生成するときには、IronPDFをバックグラウンドスレッドで実行して完了時にUIに通知するのが理にかなっています。 イベント駆動型設計がどのように役立つかを紹介します: 背景作業者を使用して非同期にPDFを生成する 各段階が完了するたびにイベントを発生させる イベントデータオブジェクトを使用して結果データを渡す コード例 - 非同期でPDFを生成する 次の例は、IronPDFを使用したイベント処理の完全なコードです: using System; using System.ComponentModel; using IronPdf; namespace IronPdfEventHandlerExample { // 1. Define custom EventArgs to carry event data public class PdfGeneratedEventArgs : EventArgs { public string FilePath { get; set; } } // 2. Main class with event, BackgroundWorker, and logic public class PdfGenerator { // Declare the public event using EventHandler<T> public event EventHandler<PdfGeneratedEventArgs> PdfGenerated; private readonly BackgroundWorker _worker; public PdfGenerator() { _worker = new BackgroundWorker(); _worker.DoWork += OnDoWork; _worker.RunWorkerCompleted += OnRunWorkerCompleted; } // Start the async operation public void GenerateAsync(string html, string outputPath) { _worker.RunWorkerAsync(new Tuple<string, string>(html, outputPath)); } // Perform PDF generation in background private void OnDoWork(object sender, DoWorkEventArgs e) { var (html, path) = (Tuple<string, string>)e.Argument; var renderer = new HtmlToPdf(); var pdf = renderer.RenderHtmlAsPdf(html); pdf.SaveAs(path); e.Result = path; } // Notify subscribers when the PDF is ready private void OnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { var path = e.Result as string; PdfGenerated?.Invoke(this, new PdfGeneratedEventArgs { FilePath = path }); } } // 3. Program to wire it all together class Program { public static void Main(string[] args) { var generator = new PdfGenerator(); // Subscribe to the PdfGenerated event generator.PdfGenerated += OnPdfGenerated; Console.WriteLine("Generating PDF asynchronously..."); generator.GenerateAsync("<h1>Hello, IronPDF!</h1>", "output.pdf"); Console.WriteLine("Press any key to exit after generation."); Console.ReadKey(); } // Event handler for when the PDF is ready static void OnPdfGenerated(object sender, PdfGeneratedEventArgs e) { Console.WriteLine($"PDF generated at: {e.FilePath}"); } } } using System; using System.ComponentModel; using IronPdf; namespace IronPdfEventHandlerExample { // 1. Define custom EventArgs to carry event data public class PdfGeneratedEventArgs : EventArgs { public string FilePath { get; set; } } // 2. Main class with event, BackgroundWorker, and logic public class PdfGenerator { // Declare the public event using EventHandler<T> public event EventHandler<PdfGeneratedEventArgs> PdfGenerated; private readonly BackgroundWorker _worker; public PdfGenerator() { _worker = new BackgroundWorker(); _worker.DoWork += OnDoWork; _worker.RunWorkerCompleted += OnRunWorkerCompleted; } // Start the async operation public void GenerateAsync(string html, string outputPath) { _worker.RunWorkerAsync(new Tuple<string, string>(html, outputPath)); } // Perform PDF generation in background private void OnDoWork(object sender, DoWorkEventArgs e) { var (html, path) = (Tuple<string, string>)e.Argument; var renderer = new HtmlToPdf(); var pdf = renderer.RenderHtmlAsPdf(html); pdf.SaveAs(path); e.Result = path; } // Notify subscribers when the PDF is ready private void OnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { var path = e.Result as string; PdfGenerated?.Invoke(this, new PdfGeneratedEventArgs { FilePath = path }); } } // 3. Program to wire it all together class Program { public static void Main(string[] args) { var generator = new PdfGenerator(); // Subscribe to the PdfGenerated event generator.PdfGenerated += OnPdfGenerated; Console.WriteLine("Generating PDF asynchronously..."); generator.GenerateAsync("<h1>Hello, IronPDF!</h1>", "output.pdf"); Console.WriteLine("Press any key to exit after generation."); Console.ReadKey(); } // Event handler for when the PDF is ready static void OnPdfGenerated(object sender, PdfGeneratedEventArgs e) { Console.WriteLine($"PDF generated at: {e.FilePath}"); } } } Imports System Imports System.ComponentModel Imports IronPdf Namespace IronPdfEventHandlerExample ' 1. Define custom EventArgs to carry event data Public Class PdfGeneratedEventArgs Inherits EventArgs Public Property FilePath() As String End Class ' 2. Main class with event, BackgroundWorker, and logic Public Class PdfGenerator ' Declare the public event using EventHandler<T> Public Event PdfGenerated As EventHandler(Of PdfGeneratedEventArgs) Private ReadOnly _worker As BackgroundWorker Public Sub New() _worker = New BackgroundWorker() AddHandler _worker.DoWork, AddressOf OnDoWork AddHandler _worker.RunWorkerCompleted, AddressOf OnRunWorkerCompleted End Sub ' Start the async operation Public Sub GenerateAsync(ByVal html As String, ByVal outputPath As String) _worker.RunWorkerAsync(New Tuple(Of String, String)(html, outputPath)) End Sub ' Perform PDF generation in background Private Sub OnDoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) 'INSTANT VB TODO TASK: VB has no equivalent to C# deconstruction declarations: var(html, path) = (Tuple(Of String, String))e.Argument Dim renderer = New HtmlToPdf() Dim pdf = renderer.RenderHtmlAsPdf(html) pdf.SaveAs(path) e.Result = path End Sub ' Notify subscribers when the PDF is ready Private Sub OnRunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Dim path = TryCast(e.Result, String) RaiseEvent PdfGenerated(Me, New PdfGeneratedEventArgs With {.FilePath = path}) End Sub End Class ' 3. Program to wire it all together Friend Class Program Public Shared Sub Main(ByVal args() As String) Dim generator = New PdfGenerator() ' Subscribe to the PdfGenerated event AddHandler generator.PdfGenerated, AddressOf OnPdfGenerated Console.WriteLine("Generating PDF asynchronously...") generator.GenerateAsync("<h1>Hello, IronPDF!</h1>", "output.pdf") Console.WriteLine("Press any key to exit after generation.") Console.ReadKey() End Sub ' Event handler for when the PDF is ready Private Shared Sub OnPdfGenerated(ByVal sender As Object, ByVal e As PdfGeneratedEventArgs) Console.WriteLine($"PDF generated at: {e.FilePath}") End Sub End Class End Namespace $vbLabelText $csharpLabel コンソール出力 PDF 出力 このコードの主要な機能 public event EventHandler<PdfGeneratedEventArgs>: 型に強く依存するイベントを宣言 PdfGeneratedEventArgs: イベントデータ用のカスタムクラス BackgroundWorker: UIブロッキングを避けるために非同期実行を許可 ?.Invoke(...): 安全なイベント呼び出し Tuple<string, string>: HTMLと出力パスを背景スレッドに渡す .NETでのイベント作業のヒント 1. UIスレッドのブロッキングを避ける RunWorkerCompletedのようなイベントハンドラを使用して、バックグラウンドタスクが完了した後にのみUIを更新します。 2. 例外を優雅に処理する DoWork内で作業ロジックをtry-catchブロックでラップし、e.Errorを通じてRunWorkerCompletedに例外を渡します。 if (e.Error != null) { MessageBox.Show("Error: " + e.Error.Message); } if (e.Error != null) { MessageBox.Show("Error: " + e.Error.Message); } If e.Error IsNot Nothing Then MessageBox.Show("Error: " & e.Error.Message) End If $vbLabelText $csharpLabel 3. 必要に応じて購読解除する 長時間実行するアプリでは、イベントが不要になったときに購読解除を行ってメモリリークを避けます: pdfWorker.DoWork -= PdfWorker_DoWork; pdfWorker.DoWork -= PdfWorker_DoWork; pdfWorker.DoWork -= PdfWorker_DoWork $vbLabelText $csharpLabel 最終的な考え イベントハンドラー、デリゲートタイプ、およびイベントフィールドを使用することで、IronPDFは.NETアプリケーションに応答性と近代的なエッジを追加します。 ベースクラスでのドキュメント生成、派生クラスでの再利用可能なロジックの作成、または.NETのイベントモデルの探索にかかわらず、このパターンはスケーラブルでクリーンです。 いつこのアプローチを使用するか タスクが完了したときにイベントを発生させたい ロジックとUIの間のクリーンな分離が必要 BackgroundWorker、イベント、デリゲートを使用して作業している C#の型安全な関数ポインターメカニックを好む 検討する代替案 新しいワークフローのためのasync/awaitとTask.Run 長時間の操作中のリアルタイム更新のためのIProgress<T>、IronPDFとC#のイベントを組み合わせることで、実際に使用可能で応答性の高いPDF生成アプリを簡単に作成できます。 イベント駆動型PDF生成をあなたの.NETアプリに実装する準備ができましたか? IronPDF無料トライアルをお試しください。スムーズで非ブロッキングな体験でユーザーを満足させましょう! よくある質問 C# で HTML を PDF に変換するにはどうすればいいですか? IronPDF の RenderHtmlAsPdf メソッドを使用して、HTML 文字列を PDF に変換できます。RenderHtmlFileAsPdf を使用して HTML ファイルを PDF に変換することもできます。 なぜイベント駆動型プログラミングが.NETアプリケーションで重要なのでしょうか? .NETアプリケーションでは、イベント駆動型プログラミングはメインスレッドをブロックせずにタスクを非同期で実行できるようにすることで、応答性を高めスムーズなユーザーエクスペリエンスを保証するために重要です。 .NETプロジェクトで必要なPDF生成ツールをどのようにインストールしますか? Visual Studioのパッケージマネージャーコンソールで「Install-Package IronPdf」というコマンドを実行して、NuGet経由でIronPDFをインストールできます。 C#でイベントをどのように宣言しますか? C#では、イベントは通常『event』キーワードと『EventHandler』のようなデリゲート型を使用して宣言されます。例えば: public event EventHandler PdfGenerated;。 C#のイベント処理におけるデリゲートとは何ですか? C#のデリゲートは、型安全な関数ポインタであり、イベントに応答して呼び出されるメソッドを定義できるようにします。 C#でイベントにメソッドを追加するにはどうすればよいですか? イベントにメソッドを動的に追加するには、C#で'+='構文を使用してイベントに登録します。 カスタムEventArgsクラスの作成の目的は何ですか? カスタムEventArgsクラスは構造化され型安全な方法でファイルパスなどのイベント固有のデータをイベントハンドラーに渡すために使用されます。 大きなPDFを生成するためにBackgroundWorkerを使用すべき理由は何ですか? BackgroundWorkerを使用すると、PDF生成タスクを非同期で実行でき、UIがブロックされるのを防ぎ、ユーザーエクスペリエンスが向上します。 .NETでのイベント処理に関するヒントは何ですか? 主なヒントとして、バックグラウンドタスクの完了後にのみUIを更新することでUIスレッドのブロックを回避したり、例外を適切に処理したり、メモリリークを防ぐために不要になったらイベントのサブスクリプションを解除するなどがあります。 .NETでイベントハンドラーを使用する代替案は何ですか? 代替案としては、より新しいワークフロー向けにasync/awaitとTask.Runを使用し、IProgressを使って長時間にわたる操作中のリアルタイム更新を行うといったものがあります。 Curtis Chau 今すぐエンジニアリングチームとチャット テクニカルライター Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。 関連する記事 更新日 9月 4, 2025 RandomNumberGenerator C# RandomNumberGenerator C#クラスを使用すると、PDF生成および編集プロジェクトを次のレベルに引き上げることができます 詳しく読む 更新日 9月 4, 2025 C# String Equals(開発者向けの仕組み) 強力なPDFライブラリであるIronPDFと組み合わせることで、switchパターンマッチングは、ドキュメント処理のためのよりスマートでクリーンなロジックを構築できます 詳しく読む 更新日 8月 5, 2025 C# Switch Pattern Matching(開発者向けの仕組み) 強力なPDFライブラリであるIronPDFと組み合わせることで、switchパターンマッチングは、ドキュメント処理のためのよりスマートでクリーンなロジックを構築できます 詳しく読む .NET 10の機能(開発者向けの仕組み)C# BackgroundWorker(開発者向...
更新日 9月 4, 2025 RandomNumberGenerator C# RandomNumberGenerator C#クラスを使用すると、PDF生成および編集プロジェクトを次のレベルに引き上げることができます 詳しく読む
更新日 9月 4, 2025 C# String Equals(開発者向けの仕組み) 強力なPDFライブラリであるIronPDFと組み合わせることで、switchパターンマッチングは、ドキュメント処理のためのよりスマートでクリーンなロジックを構築できます 詳しく読む
更新日 8月 5, 2025 C# Switch Pattern Matching(開発者向けの仕組み) 強力なPDFライブラリであるIronPDFと組み合わせることで、switchパターンマッチングは、ドキュメント処理のためのよりスマートでクリーンなロジックを構築できます 詳しく読む