How to Use Progress Tracking in C# with IronOCR
IronOCR provides an event-based progress tracking system for OCR operations, allowing developers to monitor reading progress through the OcrProgress event which reports completion percentage, pages processed, and time metrics in real-time.
This example shows how to monitor OCR progress with IronOCR: subscribe to its built-in OcrProgress event and receive instant feedback including percentage, pages completed, and total pages while reading a PDF. Only a few lines are needed to get started.
-
1Install IronOCR with NuGet Package Manager
-
2Copy and run this code snippet.
var ocr = new IronOcr.IronTesseract(); ocr.OcrProgress += (s, e) => Console.WriteLine(e.ProgressPercent + "% (" + e.PagesComplete + "/" + e.TotalPages + ")"); var result = ocr.Read(new IronOcr.OcrInput().LoadPdf("file.pdf"));C# -
3Deploy to test on your live environment
Start using IronOCR in your project today with a free trial
Minimal Workflow (5 steps)
- Download a C# library for tracking reading progress
- Subscribe to the OcrProgress event
- Utilize the instance passed by the event to retrieve progress information
- Obtain progress in percentage and total duration
- Retrieve start and end times, as well as the total number of pages
How Do I Implement Progress Tracking in My OCR Application?
Progress tracking is essential when processing large documents or batches of files with OCR. The OcrProgress event can be subscribed to receive progress updates on the reading process. This is particularly useful for PDF OCR operations and when working with multipage TIFF files.
The event passes an instance containing information about the progress of the OCR job, such as the start time, total pages, progress as a percentage, duration, and end time. This functionality works seamlessly with async operations and can be combined with multithreading for enhanced performance.
The following example uses this document as a sample: "Experiences in Biodiversity Research: A Field Course" by Thea B. Gessler, Iowa State University.
using IronOcr;
using System;
var ocrTesseract = new IronTesseract();
// Subscribe to OcrProgress event
ocrTesseract.OcrProgress += (_, ocrProgressEventsArgs) =>
{
Console.WriteLine("Start time: " + ocrProgressEventsArgs.StartTimeUTC.ToString());
Console.WriteLine("Total pages number: " + ocrProgressEventsArgs.TotalPages);
Console.WriteLine("Progress(%) | Duration");
Console.WriteLine(" " + ocrProgressEventsArgs.ProgressPercent + "% | " + ocrProgressEventsArgs.Duration.TotalSeconds + "s");
Console.WriteLine("End time: " + ocrProgressEventsArgs.EndTimeUTC.ToString());
Console.WriteLine("----------------------------------------------");
};
using var input = new OcrInput();
input.LoadPdf("Experiences-in-Biodiversity-Research-A-Field-Course.pdf");
// Progress events will fire during the read operation
var result = ocrTesseract.Read(input);Imports IronOcr
Imports System
Private ocrTesseract = New IronTesseract()
' Subscribe to OcrProgress event
Private ocrTesseract.OcrProgress += Sub(underscore, ocrProgressEventsArgs)
Console.WriteLine("Start time: " & ocrProgressEventsArgs.StartTimeUTC.ToString())
Console.WriteLine("Total pages number: " & ocrProgressEventsArgs.TotalPages)
Console.WriteLine("Progress(%) | Duration")
Console.WriteLine(" " & ocrProgressEventsArgs.ProgressPercent & "% | " & ocrProgressEventsArgs.Duration.TotalSeconds & "s")
Console.WriteLine("End time: " & ocrProgressEventsArgs.EndTimeUTC.ToString())
Console.WriteLine("----------------------------------------------")
End Sub
Private input = New OcrInput()
input.LoadPdf("Experiences-in-Biodiversity-Research-A-Field-Course.pdf")
' Progress events will fire during the read operation
Dim result = ocrTesseract.Read(input)What Progress Information Can I Access from the Event?
The OcrProgress event provides comprehensive progress data that helps monitor and optimize OCR performance. Each property serves a specific purpose in tracking the operation:
ProgressPercent: Progress of the OCR job as a percentage of pages completed, ranging from 0 to 100. Useful for updating progress bars in GUI applications.TotalPages: Total number of pages being processed by the OCR engine. Essential for calculating estimated completion times.PagesComplete: Number of pages where OCR reading has been fully completed. This count increases gradually as pages are processed.Duration: Total duration of the OCR job, indicating time taken for the entire process to complete. Measured inTimeSpanformat and updated every time the event triggers.StartTimeUTC: Date and time when the OCR job started, represented in Coordinated Universal Time (UTC) format.EndTimeUTC: Date and time when the OCR job was 100% completed in UTC format. This property is null while OCR is in progress and gets populated once the process finishes.
Advanced Progress Tracking Implementation
For production applications, implement more sophisticated progress tracking. This example includes error handling and detailed logging:
using IronOcr;
using System;
using System.Diagnostics;
public class OcrProgressTracker
{
private readonly IronTesseract _tesseract;
private Stopwatch _stopwatch;
private int _lastReportedPercent = 0;
public OcrProgressTracker()
{
_tesseract = new IronTesseract();
// Configure for optimal performance
_tesseract.Language = OcrLanguage.EnglishBest;
_tesseract.Configuration.ReadBarCodes = false;
// Subscribe to progress event
_tesseract.OcrProgress += OnOcrProgress;
}
private void OnOcrProgress(object sender, OcrProgressEventsArgs e)
{
// Only report significant progress changes (every 10%)
if (e.ProgressPercent - _lastReportedPercent >= 10 || e.ProgressPercent == 100)
{
_lastReportedPercent = e.ProgressPercent;
Console.WriteLine($"Progress: {e.ProgressPercent}%");
Console.WriteLine($"Pages: {e.PagesComplete}/{e.TotalPages}");
Console.WriteLine($"Elapsed: {e.Duration.TotalSeconds:F1}s");
// Estimate remaining time
if (e.ProgressPercent > 0 && e.ProgressPercent < 100)
{
var estimatedTotal = e.Duration.TotalSeconds / (e.ProgressPercent / 100.0);
var remaining = estimatedTotal - e.Duration.TotalSeconds;
Console.WriteLine($"Estimated remaining: {remaining:F1}s");
}
Console.WriteLine("---");
}
}
public OcrResult ProcessDocument(string filePath)
{
_stopwatch = Stopwatch.StartNew();
using var input = new OcrInput();
input.LoadPdf(filePath);
// Apply image filters for better accuracy
input.Deskew();
input.DeNoise();
var result = _tesseract.Read(input);
_stopwatch.Stop();
Console.WriteLine($"Total processing time: {_stopwatch.Elapsed.TotalSeconds:F1}s");
return result;
}
}Imports IronOcr
Imports System
Imports System.Diagnostics
Public Class OcrProgressTracker
Private ReadOnly _tesseract As IronTesseract
Private _stopwatch As Stopwatch
Private _lastReportedPercent As Integer = 0
Public Sub New()
_tesseract = New IronTesseract()
' Configure for optimal performance
_tesseract.Language = OcrLanguage.EnglishBest
_tesseract.Configuration.ReadBarCodes = False
' Subscribe to progress event
AddHandler _tesseract.OcrProgress, AddressOf OnOcrProgress
End Sub
Private Sub OnOcrProgress(sender As Object, e As OcrProgressEventsArgs)
' Only report significant progress changes (every 10%)
If e.ProgressPercent - _lastReportedPercent >= 10 OrElse e.ProgressPercent = 100 Then
_lastReportedPercent = e.ProgressPercent
Console.WriteLine($"Progress: {e.ProgressPercent}%")
Console.WriteLine($"Pages: {e.PagesComplete}/{e.TotalPages}")
Console.WriteLine($"Elapsed: {e.Duration.TotalSeconds:F1}s")
' Estimate remaining time
If e.ProgressPercent > 0 AndAlso e.ProgressPercent < 100 Then
Dim estimatedTotal = e.Duration.TotalSeconds / (e.ProgressPercent / 100.0)
Dim remaining = estimatedTotal - e.Duration.TotalSeconds
Console.WriteLine($"Estimated remaining: {remaining:F1}s")
End If
Console.WriteLine("---")
End If
End Sub
Public Function ProcessDocument(filePath As String) As OcrResult
_stopwatch = Stopwatch.StartNew()
Using input As New OcrInput()
input.LoadPdf(filePath)
' Apply image filters for better accuracy
input.Deskew()
input.DeNoise()
Dim result = _tesseract.Read(input)
_stopwatch.Stop()
Console.WriteLine($"Total processing time: {_stopwatch.Elapsed.TotalSeconds:F1}s")
Return result
End Using
End Function
End ClassIntegrating Progress Tracking with UI Applications
When building desktop applications with Windows Forms or WPF, progress tracking becomes crucial for user experience. The progress event can update UI elements safely:
using System;
using System.Windows.Forms;
using IronOcr;
public partial class OcrForm : Form
{
private IronTesseract _tesseract;
private ProgressBar progressBar;
private Label statusLabel;
public OcrForm()
{
InitializeComponent();
_tesseract = new IronTesseract();
_tesseract.OcrProgress += UpdateProgress;
}
private void UpdateProgress(object sender, OcrProgressEventsArgs e)
{
// Ensure UI updates happen on the main thread
if (InvokeRequired)
{
BeginInvoke(new Action(() => UpdateProgress(sender, e)));
return;
}
progressBar.Value = e.ProgressPercent;
statusLabel.Text = $"Processing page {e.PagesComplete} of {e.TotalPages}";
// Show completion message
if (e.ProgressPercent == 100)
{
MessageBox.Show($"OCR completed in {e.Duration.TotalSeconds:F1} seconds");
}
}
}Imports System
Imports System.Windows.Forms
Imports IronOcr
Public Partial Class OcrForm
Inherits Form
Private _tesseract As IronTesseract
Private progressBar As ProgressBar
Private statusLabel As Label
Public Sub New()
InitializeComponent()
_tesseract = New IronTesseract()
AddHandler _tesseract.OcrProgress, AddressOf UpdateProgress
End Sub
Private Sub UpdateProgress(sender As Object, e As OcrProgressEventsArgs)
' Ensure UI updates happen on the main thread
If InvokeRequired Then
BeginInvoke(New Action(Sub() UpdateProgress(sender, e)))
Return
End If
progressBar.Value = e.ProgressPercent
statusLabel.Text = $"Processing page {e.PagesComplete} of {e.TotalPages}"
' Show completion message
If e.ProgressPercent = 100 Then
MessageBox.Show($"OCR completed in {e.Duration.TotalSeconds:F1} seconds")
End If
End Sub
End ClassWorking with Large Documents and Timeouts
When processing extensive documents, progress tracking becomes even more valuable. Combine it with timeout settings and abort tokens for better control:
using IronOcr;
using System;
using System.Threading;
public async Task ProcessLargeDocumentWithTimeout()
{
var cts = new CancellationTokenSource();
var tesseract = new IronTesseract();
// Set a timeout of 5 minutes
cts.CancelAfter(TimeSpan.FromMinutes(5));
tesseract.OcrProgress += (s, e) =>
{
Console.WriteLine($"Progress: {e.ProgressPercent}% - Page {e.PagesComplete}/{e.TotalPages}");
// Check if we should cancel based on progress
if (e.Duration.TotalMinutes > 4 && e.ProgressPercent < 50)
{
Console.WriteLine("Processing too slow, cancelling...");
cts.Cancel();
}
};
try
{
using var input = new OcrInput();
input.LoadPdf("large-document.pdf");
var result = await Task.Run(() =>
tesseract.Read(input), cts.Token);
Console.WriteLine("OCR completed successfully");
}
catch (OperationCanceledException)
{
Console.WriteLine("OCR operation was cancelled");
}
}
Best Practices for Progress Tracking
- Frequency of Updates: The
OcrProgressevent fires frequently during processing. Consider filtering updates to avoid overwhelming your UI or logs. - Performance Impact: Progress tracking has minimal performance overhead, but excessive logging or UI updates can slow down the OCR process.
- Memory Management: For large TIFF files or PDFs, monitor memory usage alongside progress to ensure optimal performance.
- Error Handling: Always include error handling in your progress event handlers to prevent exceptions from disrupting the OCR process.
- Thread Safety: When updating UI elements from the progress event, ensure proper thread synchronization using
InvokeorBeginInvokemethods.
Conclusion
Progress tracking in IronOCR provides essential visibility into OCR operations, enabling developers to create responsive applications that keep users informed about processing status. By leveraging the OcrProgress event effectively, you can build professional applications that handle everything from single-page documents to extensive PDF files with confidence.
For more advanced OCR techniques, explore our guides on image filters and result objects to further enhance your OCR implementations.
Frequently Asked Questions
What is the OcrProgress event in IronOCR?
The OcrProgress event in IronOCR is an event-based progress tracking system that provides updates on the OCR process, including completion percentage, pages processed, and time metrics in real-time.
How can I monitor OCR progress in real-time using IronOCR?
You can monitor OCR progress in real-time by subscribing to the OcrProgress event, which gives you instant feedback on the percentage completed, the number of pages processed, and the total pages read.
What kind of progress data does the OcrProgress event provide?
The OcrProgress event provides data on progress percentage, total pages being processed, pages completed, duration of the job, start and end times in UTC, which helps in tracking the OCR operation.
Can IronOCR's progress tracking be used in async operations?
Yes, IronOCR's progress tracking can be seamlessly integrated with async operations, making it suitable for handling large document processing efficiently.
How do I integrate progress tracking in a Windows Forms application using IronOCR?
In a Windows Forms application, you can use the OcrProgress event to update UI elements like progress bars and labels safely, leveraging Invoke or BeginInvoke methods for thread safety.
Is there a recommended frequency for OcrProgress updates?
While the OcrProgress event fires frequently, it's recommended to filter updates to avoid overwhelming your UI or logs, which can impact performance.
How can IronOCR's progress tracking improve the processing of large documents?
When dealing with large documents, IronOCR's progress tracking allows for better control with timeout settings and abort tokens, providing a mechanism to handle slow processing efficiently.
Does progress tracking in IronOCR affect performance?
Progress tracking in IronOCR has minimal performance overhead, although excessive logging or UI updates based on progress events may slow down the overall OCR process.
What best practices should I follow for using progress tracking in IronOCR?
Best practices include managing update frequencies, ensuring thread safety when updating UI elements, and incorporating error handling to maintain smooth OCR operations.
Can IronOCR be used for tracking progress in multi-threaded environments?
Yes, IronOCR's progress tracking can be combined with multi-threading to enhance OCR performance, handling multiple documents or large files more efficiently.

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.