Zum Fußzeileninhalt springen
.NET HILFE

C# Events (Wie es für Entwickler funktioniert)

Events in C# are a fundamental part of event-driven programming. They allow objects to communicate and notify others when something of interest happens. In this guide, we will explore events and how to declare and use them. Let’s break it down step by step to ensure a clear understanding. We'll also explore IronPDF for PDF operations in C# applications.

What Are Events in C#?

Events in C# enable communication between objects. When an event is raised, other objects can respond to it. Events rely on delegates, which act as type-safe pointers to methods. An event delegate type defines the signature of methods that can handle the public event, ensuring consistency in event data handling.

Core Components of Events

To fully understand events, let’s look at their main components:

1. Publisher Class

The publisher class is the source of the event. It is responsible for declaring the event and raising it when a specific action or condition occurs. This process typically involves an event handler method to determine when the event occurs. The publisher also uses an event delegate to define the signature of the methods that can handle the event. For example, in a graphical user interface (GUI), a button control acts as the publisher when it raises a "Click" event.

2. Subscriber Class

The subscriber class listens for events and reacts to them. A subscriber registers its interest in an event by attaching an event handling method to the event. When the publisher raises the event, the subscriber’s event handler method executes. A single event can have multiple subscribers, each responding differently when the event happens.

3. Delegates

Delegates are the foundation of events in C#. They are type-safe pointers to methods and define the contract that all event handlers must follow. Delegates ensure that only methods with a specific signature can handle the event, providing a consistent and error-free event-handling mechanism.

4. Event Handlers

Event handlers are methods in the subscriber class that are executed when an event is triggered. They contain the logic to handle the event, such as updating the UI, logging data, or performing calculations. The signature of an event handler must match the delegate type associated with the event. Additionally, other classes can use event handlers to react to shared events. It makes it easier to implement events in a modular and reusable way.

5. Event Data

In many cases, events need to convey additional information to subscribers. This is achieved using event data classes, which are derived from the base EventArgs class. The event data contains specific details about the event, such as a message, status, or other relevant information.

How to Declare and Use Events in C#

Step 1: Declare a Delegate

Delegates define the method signature for event handlers. In this example, we create a delegate to represent the event handler with two parameters: object sender and EventArgs e.

public delegate void MyEventHandler(object sender, EventArgs e);
public delegate void MyEventHandler(object sender, EventArgs e);
Public Delegate Sub MyEventHandler(ByVal sender As Object, ByVal e As EventArgs)
$vbLabelText   $csharpLabel

Step 2: Declare an Event

Events are declared using the event keyword and are based on the delegate type. Here’s an example:

public class Publisher
{
    public event MyEventHandler Notify; // Declare the event.
}
public class Publisher
{
    public event MyEventHandler Notify; // Declare the event.
}
Public Class Publisher
	Public Event Notify As MyEventHandler ' Declare the event.
End Class
$vbLabelText   $csharpLabel

Step 3: Raise the Event

The event is raised by calling the delegate and passing the necessary parameters.

public void TriggerEvent()
{
    if (Notify != null) // Check if there are subscribers.
    {
        Notify(this, EventArgs.Empty); // Raise the event.
    }
}
public void TriggerEvent()
{
    if (Notify != null) // Check if there are subscribers.
    {
        Notify(this, EventArgs.Empty); // Raise the event.
    }
}
Public Sub TriggerEvent()
	If Notify IsNot Nothing Then ' Check if there are subscribers.
		Notify(Me, EventArgs.Empty) ' Raise the event.
	End If
End Sub
$vbLabelText   $csharpLabel

Step 4: Subscribe to the Event

Subscribers register event handlers using the += operator:

Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber();
publisher.Notify += subscriber.OnNotify; // Subscribe to the event.
Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber();
publisher.Notify += subscriber.OnNotify; // Subscribe to the event.
Dim publisher As New Publisher()
Dim subscriber As New Subscriber()
publisher.Notify += subscriber.OnNotify ' Subscribe to the event.
$vbLabelText   $csharpLabel

Step 5: Handle the Event

An event handler is a method in the subscriber class that matches the delegate signature:

public void OnNotify(object sender, EventArgs e)
{
    Console.WriteLine("Event received!");
}
public void OnNotify(object sender, EventArgs e)
{
    Console.WriteLine("Event received!");
}
Public Sub OnNotify(ByVal sender As Object, ByVal e As EventArgs)
	Console.WriteLine("Event received!")
End Sub
$vbLabelText   $csharpLabel

IronPDF: C# PDF Library

IronPDF, a versatile library for working with PDFs in .NET, integrates seamlessly with C# applications. Combined with events in C#, it can provide a dynamic way to handle real-time scenarios like progress updates, error handling or notifications during PDF generation or manipulation. Let’s explore this relationship engagingly. In C#, events are a way to signal that something has happened. They allow one part of your program to notify other parts about specific occurrences, such as a file being processed, a task completed, or an error encountered.

How Does IronPDF Fit?

IronPDF allows you to generate, modify, and secure PDFs, and integrating it with events can make your application more interactive. For instance:

  • Progress Tracking: Notify subscribers about the percentage of completion when generating a large PDF report.
  • Error Handling: Trigger an event if an issue arises during PDF rendering or saving.
  • Custom Actions: Execute custom logic, like logging or UI updates, after specific PDF operations.

Example: Generating a PDF with Event Notifications

Here’s a simple example to demonstrate using IronPDF with events:

using IronPdf;
using System;

// Program class
class Program
{
    // Define a custom event for progress updates
    public static event Action<int> ProgressUpdated;

    public static void Main()
    {
        License.LicenseKey = "License-Key";
        // Subscribe to the ProgressUpdated event
        ProgressUpdated += DisplayProgress;

        Console.WriteLine("Generating PDF...");
        GeneratePdf(); // Generate the PDF
    }

    // Method to generate PDF and trigger progress updates
    static void GeneratePdf()
    {
        try
        {
            var Renderer = new ChromePdfRenderer();
            for (int i = 0; i <= 100; i += 20)
            {
                // Simulate progress
                System.Threading.Thread.Sleep(500);
                ProgressUpdated?.Invoke(i); // Trigger event with progress value
            }
            // Generate a PDF
            var PdfDocument = Renderer.RenderHtmlAsPdf("<h1>Hello, IronPDF with Events!</h1>");
            PdfDocument.SaveAs("IronPDF/example.pdf");
            ProgressUpdated?.Invoke(100); // Final update
            Console.WriteLine("PDF generated successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }

    // Event handler to display progress
    static void DisplayProgress(int progress)
    {
        Console.WriteLine($"Progress: {progress}%");
    }
}
using IronPdf;
using System;

// Program class
class Program
{
    // Define a custom event for progress updates
    public static event Action<int> ProgressUpdated;

    public static void Main()
    {
        License.LicenseKey = "License-Key";
        // Subscribe to the ProgressUpdated event
        ProgressUpdated += DisplayProgress;

        Console.WriteLine("Generating PDF...");
        GeneratePdf(); // Generate the PDF
    }

    // Method to generate PDF and trigger progress updates
    static void GeneratePdf()
    {
        try
        {
            var Renderer = new ChromePdfRenderer();
            for (int i = 0; i <= 100; i += 20)
            {
                // Simulate progress
                System.Threading.Thread.Sleep(500);
                ProgressUpdated?.Invoke(i); // Trigger event with progress value
            }
            // Generate a PDF
            var PdfDocument = Renderer.RenderHtmlAsPdf("<h1>Hello, IronPDF with Events!</h1>");
            PdfDocument.SaveAs("IronPDF/example.pdf");
            ProgressUpdated?.Invoke(100); // Final update
            Console.WriteLine("PDF generated successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }

    // Event handler to display progress
    static void DisplayProgress(int progress)
    {
        Console.WriteLine($"Progress: {progress}%");
    }
}
Imports IronPdf
Imports System

' Program class
Friend Class Program
	' Define a custom event for progress updates
	Public Shared Event ProgressUpdated As Action(Of Integer)

	Public Shared Sub Main()
		License.LicenseKey = "License-Key"
		' Subscribe to the ProgressUpdated event
		AddHandler Me.ProgressUpdated, AddressOf DisplayProgress

		Console.WriteLine("Generating PDF...")
		GeneratePdf() ' Generate the PDF
	End Sub

	' Method to generate PDF and trigger progress updates
	Private Shared Sub GeneratePdf()
		Try
			Dim Renderer = New ChromePdfRenderer()
			For i As Integer = 0 To 100 Step 20
				' Simulate progress
				System.Threading.Thread.Sleep(500)
				RaiseEvent ProgressUpdated(i)
			Next i
			' Generate a PDF
			Dim PdfDocument = Renderer.RenderHtmlAsPdf("<h1>Hello, IronPDF with Events!</h1>")
			PdfDocument.SaveAs("IronPDF/example.pdf")
			RaiseEvent ProgressUpdated(100)
			Console.WriteLine("PDF generated successfully!")
		Catch ex As Exception
			Console.WriteLine($"Error: {ex.Message}")
		End Try
	End Sub

	' Event handler to display progress
	Private Shared Sub DisplayProgress(ByVal progress As Integer)
		Console.WriteLine($"Progress: {progress}%")
	End Sub
End Class
$vbLabelText   $csharpLabel

C# Events (How it Works for Developers): Figure 1 - Output

Conclusion

C# Events (How it Works for Developers): Figure 2 - Licensing

Events in C# when combined with IronPDF create a powerful system for dynamic PDF generation and management. Events provide a clean, efficient way to handle PDF operations asynchronously, while IronPDF offers robust functionality for PDF creation, editing, and manipulation across .NET platforms. IronPDF offers a free trial to test all features without limitations. Commercial licenses start at $799 and provide access to the complete suite of PDF generation and processing capabilities.

Häufig gestellte Fragen

Wie kann ich C#-Ereignisse in meiner Anwendung implementieren?

Um C#-Ereignisse zu implementieren, müssen Sie einen Delegaten definieren, der die Signatur des Ereignishandlers angibt, das Ereignis mit diesem Delegaten deklarieren, das Ereignis zur passenden Zeit auslösen und sich mit einer Methode, die der Delegatensignatur entspricht, zu dem Ereignis anmelden.

Was sind die Kernelemente von C#-Ereignissen?

Zu den Kernelementen von C#-Ereignissen gehören der Herausgeber, der das Ereignis deklariert und auslöst; der Abonnent, der das Ereignis empfängt; Delegaten, die als typsichere Zeiger auf Methoden fungieren; Ereignishandler, die ausgeführt werden, wenn das Ereignis ausgelöst wird; und Ereignisdaten, die Informationen zum Ereignis an die Abonnenten übermitteln.

Wie kann eine PDF-Bibliothek das Ereignishandling in C# verbessern?

Eine PDF-Bibliothek wie IronPDF kann das Ereignishandling in C# verbessern, indem Sie ereignisgesteuerte Benachrichtigungen in PDF-Verarbeitungsvorgänge integrieren. Dazu können Echtzeit-Fortschrittsanzeigen, Fehlerbenachrichtigungen und die Ausführung benutzerdefinierter Logik nach bestimmten PDF-Operationen gehören.

Wie unterstützen Delegaten das Ereignishandling in C#?

Delegaten in C# unterstützen das Ereignishandling, indem sie die Methodensignatur definieren, der Ereignishandler folgen müssen. Sie stellen sicher, dass nur Methoden mit der richtigen Signatur verwendet werden können, um das Ereignis zu behandeln, und gewährleisten Typsicherheit und Konsistenz.

Welche Rolle spielen Ereignishandler bei C#-Ereignissen?

Ereignishandler sind Methoden, die in Reaktion auf ein ausgelöstes Ereignis ausgeführt werden. Sie enthalten die nötige Logik zum Umgang mit dem Ereignis und müssen der vom Delegaten des Ereignisses definierten Signatur entsprechen.

Wie können C#-Ereignisse zur dynamischen PDF-Erstellung verwendet werden?

C#-Ereignisse können zur dynamischen PDF-Erstellung verwendet werden, indem ereignisgesteuerte Benachrichtigungen in den Prozess integriert werden. Dies ermöglicht es, den Fortschritt zu verfolgen, Fehler zu behandeln und benutzerdefinierte Aktionen während der PDF-Erstellung mit einer Bibliothek wie IronPDF auszuführen.

Schritte zum Auslösen eines Ereignisses in C#?

Um ein Ereignis in C# auszulösen, müssen Sie zunächst das Ereignis mit einem Delegaten deklarieren. Dann, innerhalb der Herausgeberklasse, lösen Sie das Ereignis aus, indem Sie es aufrufen, wenn eine bestimmte Bedingung erfüllt ist. Abonnenten, die Ereignishandler angebracht haben, führen ihre jeweiligen Methoden als Antwort aus.

Wie verbessern C#-Ereignisse die PDF-Verarbeitung in .NET-Anwendungen?

C#-Ereignisse verbessern die PDF-Verarbeitung in .NET-Anwendungen, indem sie eine asynchrone Bearbeitung der PDF-Operationen ermöglichen. Dies erlaubt Echtzeit-Updates, Fehlererkennung und die Ausführung benutzerdefinierter Logik, wodurch der PDF-Managementprozess dynamischer und reaktionsfähiger wird.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen