Zum Fußzeileninhalt springen
.NET HILFE

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

Generating PDFs with IronPDF is a common task for .NET developers—especially when building dynamic reports, invoices, or document automation systems. But if you’ve ever triggered PDF generation on the main UI thread in a Windows Forms or WPF app, you’ve likely seen your user interface freeze or become unresponsive. This is especially true when rendering large HTML content or processing complex PDF layouts.

That’s where the C# BackgroundWorker class comes in. This article walks through how to integrate IronPDF with BackgroundWorker to handle asynchronous operations in a desktop app without locking up the UI.

Why Use BackgroundWorker with IronPDF?

Keep Your UI Responsive

When you run CPU-heavy or IO-bound tasks like PDF generation on the main thread, it locks up the UI. Users can’t click, drag, or interact with the application while it’s busy. By using a BackgroundWorker object, you can move the work to a separate thread, keeping your interface snappy and usable during background processing.

Perfect for Report Generation and Long-Running Tasks

If your app involves exporting data, converting HTML to PDF, or rendering detailed reports—offloading that to a background worker makes your application more professional and performant.

Compatible with Legacy WinForms Apps

Although modern apps often use async/await, many older projects still benefit from BackgroundWorker for its simplicity and design-time support in Visual Studio.

What is IronPDF?

C# BackgroundWorker (How it Works for Developers): Figure 1 - IronPDF

IronPDF is a powerful .NET library designed for generating, editing, and working with PDF documents in C#. It uses a headless Chromium browser under the hood, allowing developers to convert HTML, CSS, JavaScript, and even complex web pages into accurate, print-quality PDFs. Unlike traditional PDF generators, IronPDF renders documents exactly as they would appear in a browser—matching layout, fonts, images, and styles pixel-for-pixel.

Key Features

  • HTML to PDF Conversion – Render HTML strings, URLs, or full web pages into PDFs.
  • Image and Text Rendering – Add headers, footers, watermarks, and images programmatically.
  • Merging and Splitting PDFs – Combine multiple documents or extract specific pages.
  • Form Filling and Annotations – Work with interactive PDF forms.
  • No External Dependencies – Works without needing Adobe Acrobat or Microsoft Office installed.

IronPDF supports .NET Framework, .NET Core, and .NET 6/7+, making it ideal for both desktop and web-based .NET applications.

Installing IronPDF via NuGet

To get started, install IronPDF into your project using NuGet Package Manager:

Install-Package IronPdf

This will add all necessary references so you can begin using IronPDF’s ChromePdfRenderer, HtmlToPdf, and other powerful features.

For this example, we’ll use a Windows Forms application created with Visual Studio, with a button that triggers PDF generation and a label to indicate when the process is complete.

Implementing BackgroundWorker for IronPDF

Now, we'll use the following code examples to break down the process of using BackgroundWorker in a structured and safe way:

Step 1 – Define the BackgroundWorker

You can create and configure a BackgroundWorker either in the designer or in code. Here’s the code approach:

private void SetupBackgroundWorker()
{
    // new backgroundworker worker instance
    worker = new BackgroundWorker(); // dowork event handler
    worker.DoWork += PdfWorker_DoWork;
    worker.RunWorkerCompleted += PdfWorker_RunWorkerCompleted; // final result handler
}
private void SetupBackgroundWorker()
{
    // new backgroundworker worker instance
    worker = new BackgroundWorker(); // dowork event handler
    worker.DoWork += PdfWorker_DoWork;
    worker.RunWorkerCompleted += PdfWorker_RunWorkerCompleted; // final result handler
}
Private Sub SetupBackgroundWorker()
	' new backgroundworker worker instance
	worker = New BackgroundWorker() ' dowork event handler
	worker.DoWork += PdfWorker_DoWork
	worker.RunWorkerCompleted += PdfWorker_RunWorkerCompleted ' final result handler
End Sub
$vbLabelText   $csharpLabel

This initializes the worker and wires up the necessary events for background execution and completion.

Step 2 – Handle the DoWork Event

The DoWork method runs on a different thread, performing the background operation (generating the PDF):

private void PdfWorker_DoWork(object sender, DoWorkEventArgs e)
{
    var Renderer = new ChromePdfRenderer();
    // Simulate input from UI or parameters
    string htmlContent = "<h1>Monthly Report</h1><p>Generated with IronPDF.</p>";
    string outputPath = Path.Combine(Environment.CurrentDirectory, "Report.pdf");
    // Generate PDF
    var pdf = Renderer.RenderHtmlAsPdf(htmlContent);
    pdf.SaveAs(outputPath);
    // Optionally pass result info
    e.Result = outputPath; // pass value to RunWorkerCompleted
}
private void PdfWorker_DoWork(object sender, DoWorkEventArgs e)
{
    var Renderer = new ChromePdfRenderer();
    // Simulate input from UI or parameters
    string htmlContent = "<h1>Monthly Report</h1><p>Generated with IronPDF.</p>";
    string outputPath = Path.Combine(Environment.CurrentDirectory, "Report.pdf");
    // Generate PDF
    var pdf = Renderer.RenderHtmlAsPdf(htmlContent);
    pdf.SaveAs(outputPath);
    // Optionally pass result info
    e.Result = outputPath; // pass value to RunWorkerCompleted
}
Private Sub PdfWorker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
	Dim Renderer = New ChromePdfRenderer()
	' Simulate input from UI or parameters
	Dim htmlContent As String = "<h1>Monthly Report</h1><p>Generated with IronPDF.</p>"
	Dim outputPath As String = Path.Combine(Environment.CurrentDirectory, "Report.pdf")
	' Generate PDF
	Dim pdf = Renderer.RenderHtmlAsPdf(htmlContent)
	pdf.SaveAs(outputPath)
	' Optionally pass result info
	e.Result = outputPath ' pass value to RunWorkerCompleted
End Sub
$vbLabelText   $csharpLabel

Note: You cannot interact with UI controls here since it runs on a worker thread.

Step 3 – Use RunWorkerCompleted to Notify Completion

Once the background thread completes, you can safely update the UI with the results.

private void PdfWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Error != null)
    {
        MessageBox.Show("Error: " + e.Error.Message);
    }
    else
    {
        string savedPath = e.Result.ToString();
        MessageBox.Show("PDF created at:\n" + savedPath);
    }
}
private void PdfWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Error != null)
    {
        MessageBox.Show("Error: " + e.Error.Message);
    }
    else
    {
        string savedPath = e.Result.ToString();
        MessageBox.Show("PDF created at:\n" + savedPath);
    }
}
Imports Microsoft.VisualBasic

Private Sub PdfWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
	If e.Error IsNot Nothing Then
		MessageBox.Show("Error: " & e.Error.Message)
	Else
		Dim savedPath As String = e.Result.ToString()
		MessageBox.Show("PDF created at:" & vbLf & savedPath)
	End If
End Sub
$vbLabelText   $csharpLabel

Step 4 – Triggering BackgroundWorker from UI

Add a Start button to execute the background task when clicked:

private void btnGeneratePDF_Click(object sender, EventArgs e)
{
    if (pdfWorker == null)
        SetupBackgroundWorker();
    if (!pdfWorker.IsBusy)
    {
        btnGeneratePDF.Enabled = false;
        pdfWorker.RunWorkerAsync(); // execute method in background
    }
}
private void btnGeneratePDF_Click(object sender, EventArgs e)
{
    if (pdfWorker == null)
        SetupBackgroundWorker();
    if (!pdfWorker.IsBusy)
    {
        btnGeneratePDF.Enabled = false;
        pdfWorker.RunWorkerAsync(); // execute method in background
    }
}
Private Sub btnGeneratePDF_Click(ByVal sender As Object, ByVal e As EventArgs)
	If pdfWorker Is Nothing Then
		SetupBackgroundWorker()
	End If
	If Not pdfWorker.IsBusy Then
		btnGeneratePDF.Enabled = False
		pdfWorker.RunWorkerAsync() ' execute method in background
	End If
End Sub
$vbLabelText   $csharpLabel

Full Code Example

Here’s everything tied together in a single working Windows Forms snippet:

using System;
using System.ComponentModel;
using IronPdf;
using System.IO;
using System.Windows.Forms;
namespace TestApp
{
    public partial class Form1 : Form
    {
        private BackgroundWorker worker;
        public Form1()
        {
            InitializeComponent();
            SetupBackgroundWorker();        }
        private void SetupBackgroundWorker()
        {
            worker = new BackgroundWorker();
            worker.DoWork += PdfWorker_DoWork;
            worker.RunWorkerCompleted += PdfWorker_RunWorkerCompleted;
        }
        private void btnGeneratePDF_Click(object sender, EventArgs e)
        {
            if (!worker.IsBusy)
            {
                btnGeneratePDF.Enabled = false;
                worker.RunWorkerAsync();
            }
        }
        private void PdfWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            var Renderer = new ChromePdfRenderer();
            string htmlContent = "<h1>Report</h1><p>This PDF was generated in the background.</p>";
            string outputPath = Path.Combine(Environment.CurrentDirectory, "Report.pdf");
            var pdf = Renderer.RenderHtmlAsPdf(htmlContent);
            pdf.SaveAs(outputPath);
            e.Result = outputPath;
        }
        private void PdfWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btnGeneratePDF.Enabled = true;
            if (e.Error != null)
            {
                MessageBox.Show("Failed: " + e.Error.Message);
            }
            else
            {
                MessageBox.Show("PDF created: " + e.Result.ToString());
            }
        }
        private void btnGeneratePDF_Click_1(object sender, EventArgs e)
        {
            if (!worker.IsBusy)
            {
                btnGeneratePDF.Enabled = false;
                worker.RunWorkerAsync();
            }
        }
    }
}
using System;
using System.ComponentModel;
using IronPdf;
using System.IO;
using System.Windows.Forms;
namespace TestApp
{
    public partial class Form1 : Form
    {
        private BackgroundWorker worker;
        public Form1()
        {
            InitializeComponent();
            SetupBackgroundWorker();        }
        private void SetupBackgroundWorker()
        {
            worker = new BackgroundWorker();
            worker.DoWork += PdfWorker_DoWork;
            worker.RunWorkerCompleted += PdfWorker_RunWorkerCompleted;
        }
        private void btnGeneratePDF_Click(object sender, EventArgs e)
        {
            if (!worker.IsBusy)
            {
                btnGeneratePDF.Enabled = false;
                worker.RunWorkerAsync();
            }
        }
        private void PdfWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            var Renderer = new ChromePdfRenderer();
            string htmlContent = "<h1>Report</h1><p>This PDF was generated in the background.</p>";
            string outputPath = Path.Combine(Environment.CurrentDirectory, "Report.pdf");
            var pdf = Renderer.RenderHtmlAsPdf(htmlContent);
            pdf.SaveAs(outputPath);
            e.Result = outputPath;
        }
        private void PdfWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btnGeneratePDF.Enabled = true;
            if (e.Error != null)
            {
                MessageBox.Show("Failed: " + e.Error.Message);
            }
            else
            {
                MessageBox.Show("PDF created: " + e.Result.ToString());
            }
        }
        private void btnGeneratePDF_Click_1(object sender, EventArgs e)
        {
            if (!worker.IsBusy)
            {
                btnGeneratePDF.Enabled = false;
                worker.RunWorkerAsync();
            }
        }
    }
}
Imports System
Imports System.ComponentModel
Imports IronPdf
Imports System.IO
Imports System.Windows.Forms
Namespace TestApp
	Partial Public Class Form1
		Inherits Form

		Private worker As BackgroundWorker
		Public Sub New()
			InitializeComponent()
			SetupBackgroundWorker()
		End Sub
		Private Sub SetupBackgroundWorker()
			worker = New BackgroundWorker()
			AddHandler worker.DoWork, AddressOf PdfWorker_DoWork
			AddHandler worker.RunWorkerCompleted, AddressOf PdfWorker_RunWorkerCompleted
		End Sub
		Private Sub btnGeneratePDF_Click(ByVal sender As Object, ByVal e As EventArgs)
			If Not worker.IsBusy Then
				btnGeneratePDF.Enabled = False
				worker.RunWorkerAsync()
			End If
		End Sub
		Private Sub PdfWorker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
			Dim Renderer = New ChromePdfRenderer()
			Dim htmlContent As String = "<h1>Report</h1><p>This PDF was generated in the background.</p>"
			Dim outputPath As String = Path.Combine(Environment.CurrentDirectory, "Report.pdf")
			Dim pdf = Renderer.RenderHtmlAsPdf(htmlContent)
			pdf.SaveAs(outputPath)
			e.Result = outputPath
		End Sub
		Private Sub PdfWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
			btnGeneratePDF.Enabled = True
			If e.Error IsNot Nothing Then
				MessageBox.Show("Failed: " & e.Error.Message)
			Else
				MessageBox.Show("PDF created: " & e.Result.ToString())
			End If
		End Sub
		Private Sub btnGeneratePDF_Click_1(ByVal sender As Object, ByVal e As EventArgs)
			If Not worker.IsBusy Then
				btnGeneratePDF.Enabled = False
				worker.RunWorkerAsync()
			End If
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

Form output

C# BackgroundWorker (How it Works for Developers): Figure 2 - Form output after PDF creation

PDF Output

C# BackgroundWorker (How it Works for Developers): Figure 3 - PDF output

Best Practices

Avoid UI Access in DoWork

The DoWork event handler runs on a different thread, so you can’t access UI elements directly. Use RunWorkerCompleted or control Invoke() calls for safe UI updates.

Support Asynchronous Cancellation

If your task is long, enable WorkerSupportsCancellation = true and monitor CancellationPending inside DoWork to support requested cancellation.

Use Report Progress Updates (Optional)

You can enable WorkerReportsProgress = true and use the ProgressChanged event to show a progress bar or messages.

Validate the Input Argument

When using RunWorkerAsync(argument), validate the argument in DoWork and return any method results through e.Result.

Conclusion

Using BackgroundWorker with IronPDF enables you to perform heavy PDF rendering tasks on a background thread, keeping your application responsive. This is especially valuable when working with WinForms or WPF apps that require responsive UI updates during long-running tasks like PDF generation.

By handling the dowork event handler, monitoring the final result, and safely updating your user interface in the runworkercompleted event, you ensure your background operations run smoothly.

While async/await is often the go-to for new applications, BackgroundWorker remains a reliable tool for legacy or WinForms projects. Whether you're exporting reports or generating documents on-the-fly, this approach will help you get the most out of IronPDF while keeping your app smooth and user-friendly.

Ready to try it yourself?

Download the free IronPDF trial and start building powerful PDF solutions in C# today. The trial gives you full access to the features showcased in this article—no credit card required.

Häufig gestellte Fragen

Wie kann ich die PDF-Erstellung in einer C# Windows Forms-Anwendung ausführen, ohne die Benutzeroberfläche einzufrieren?

Sie können die C# BackgroundWorker-Klasse in Verbindung mit IronPDF nutzen, um die PDF-Erstellung in einem separaten Thread durchzuführen. Dies stellt sicher, dass der Haupt-UI-Thread während des Prozesses reaktionsfähig bleibt.

Welche Rolle spielt der DoWork-Ereignishandler im BackgroundWorker?

Der DoWork-Ereignishandler ist der Ort, an dem Sie die langwierige Aufgabe ausführen, wie z.B. die PDF-Erstellung mit IronPDF. Er läuft in einem separaten Thread von der Benutzeroberfläche und verhindert das Einfrieren der Oberfläche.

Wie kann ich die Benutzeroberfläche mit Ergebnissen einer Hintergrundaufgabe zur PDF-Erstellung aktualisieren?

Verwenden Sie das RunWorkerCompleted-Ereignis, um die Benutzeroberfläche mit den Ergebnissen Ihrer PDF-Erstellung zu aktualisieren. Dieses Ereignis wird ausgelöst, sobald die Hintergrundaufgabe abgeschlossen ist, und ermöglicht eine sichere Interaktion mit UI-Elementen.

Welche Vorteile bietet die Verwendung von BackgroundWorker für die PDF-Verarbeitung in älteren .NET-Anwendungen?

BackgroundWorker bietet eine einfache Möglichkeit, asynchrone Operationen in Legacy-WinForms-Anwendungen zu implementieren. Er stellt ein einfaches Modell zur Verfügung, um Aufgaben wie die PDF-Verarbeitung mit IronPDF zu handhaben und dabei die Benutzeroberfläche reaktionsfähig zu halten.

Kann ich eine PDF-Erstellungsaufgabe mit BackgroundWorker abbrechen?

Ja, BackgroundWorker unterstützt die Beendigung von Aufgaben. Sie können die Beendigung implementieren, indem Sie die CancellationPending-Eigenschaft in Ihrem DoWork-Ereignishandler überprüfen und die Aufgabe sanft beenden.

Wie kann ich den Fortschritt der PDF-Erstellung mit BackgroundWorker überwachen?

Sie können den Fortschritt von der DoWork-Methode aus mit der ReportProgress-Methode des BackgroundWorker melden. Dies ermöglicht es Ihnen, die Benutzeroberfläche während der PDF-Erstellung mit Fortschrittsinformationen zu aktualisieren.

Warum sollten UI-Updates im DoWork-Ereignishandler vermieden werden?

UI-Updates sollten im DoWork-Ereignishandler vermieden werden, da dieser in einem separaten Thread läuft. Direkte UI-Manipulation könnte zu Threading-Problemen führen. Verwenden Sie stattdessen die RunWorkerCompleted- oder ProgressChanged-Ereignisse für UI-Updates.

Welche Schritte sind erforderlich, um einen BackgroundWorker für die PDF-Erstellung in C# einzurichten?

Das Einrichten eines BackgroundWorker umfasst die Initialisierung des Workers, die Behandlung der DoWork- und RunWorkerCompleted-Ereignisse und den Start der Aufgabe mit RunWorkerAsync. Dieses Setup wird verwendet, um Aufgaben wie die PDF-Erstellung mit IronPDF auszuführen.

Ist es notwendig, moderne async/await-Muster für die PDF-Erstellung in .NET-Anwendungen zu verwenden?

Obwohl moderne async/await-Muster für neue Anwendungen empfohlen werden, bleibt BackgroundWorker in älteren WinForms-Anwendungen für die Handhabung asynchroner Aufgaben wie die PDF-Erstellung mit IronPDF aufgrund seiner Einfachheit und Benutzerfreundlichkeit nützlich.

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