How to use Async and Multithreading

This article was translated from English: Does it need improvement?
Translated
View the article in English

In the ever-evolving landscape of software development, the efficient processing of large volumes of textual data remains a pivotal challenge. In this article, we explore the dynamic synergy of Async Support and Multithreading within the context of IronOCR and Tesseract. Asynchronous programming introduces a non-blocking paradigm, ensuring our applications remain nimble and responsive during the execution of OCR tasks. Simultaneously, we delve into the realm of multithreading, unraveling the potential for parallelism to significantly boost the performance of text recognition operations. Join us as we demystify the integration of these techniques, empowering developers to elevate the efficiency and responsiveness of their OCR-powered applications.

Quickstart: Use ReadAsync for Effortless Async OCR

Here’s how easy it is to get started: use IronTesseract’s ReadAsync method to perform OCR without blocking your main thread. Perfect for quickly adding responsive, non-blocking OCR capability to your application.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronOCR with NuGet Package Manager

    PM > Install-Package IronOcr

  2. Copy and run this code snippet.

    var result = await new IronOcr.IronTesseract().ReadAsync("image.png");
  3. Deploy to test on your live environment

    Start using IronOCR in your project today with a free trial
    arrow pointer

Understanding Multithreading

In IronOCR, the efficiency of image processing and OCR reading is enhanced by seamless multithreading, eliminating the need for developers to employ a specialized API. IronTesseract automatically leverages all available threads across multiple cores, optimizing system resources for swift and responsive OCR execution. This intrinsic multithreading not only simplifies development but also significantly boosts performance, showcasing a sophisticated integration of parallelism into the OCR workflow.

Here is what a multithreaded read might look like in C#:

:path=/static-assets/ocr/content-code-examples/how-to/async-simple-multithreading.cs
using IronOcr;
using System;

var ocr = new IronTesseract();

using (var input = new OcrPdfInput(@"example.pdf"))
{
    var result = ocr.Read(input);
    Console.WriteLine(result.Text);
};
Imports IronOcr
Imports System

Private ocr = New IronTesseract()

Using input = New OcrPdfInput("example.pdf")
	Dim result = ocr.Read(input)
	Console.WriteLine(result.Text)
End Using
$vbLabelText   $csharpLabel

Understanding Async Support

In the realm of Optical Character Recognition (OCR), asynchronous programming, or "async," plays a pivotal role in optimizing performance. Async support allows developers to execute OCR tasks without blocking the main thread, ensuring the application remains responsive. Imagine processing large documents or images for text recognition – async support allows the system to continue handling other tasks while OCR operations are underway.

In this section, we'll delve into the effortless integration of Async Support in IronOCR, showcasing different ways to make your OCR services non-blocking.

Using An OcrReadTask Object

When working with IronOCR, the utilization of OcrReadTask objects proves to be a valuable asset in enhancing control and flexibility within your OCR processes. These objects encapsulate OCR operations, allowing developers to manage text recognition tasks efficiently. This section provides examples of employing OcrReadTask objects in your IronOCR workflow, demonstrating how they can be leveraged to initiate and optimize OCR tasks. Whether you are orchestrating complex document processing or fine-tuning the responsiveness of your OCR-powered application, effectively utilizing OcrReadTask objects helps to maximize the capabilities of IronOCR.

:path=/static-assets/ocr/content-code-examples/how-to/async-ocrtask.cs
using IronOcr;

IronTesseract ocr = new IronTesseract();

OcrPdfInput largePdf = new OcrPdfInput("chapter1.pdf");

Func<OcrResult> reader = () =>
{
    return ocr.Read(largePdf);
};

OcrReadTask readTask = new OcrReadTask(reader.Invoke);
// Start the OCR task asynchronously
readTask.Start();

// Continue with other tasks while OCR is in progress
DoOtherTasks();

// Wait for the OCR task to complete and retrieve the result
OcrResult result = await Task.Run(() => readTask.Result);

Console.Write($"##### OCR RESULTS ###### \n {result.Text}");

largePdf.Dispose();
readTask.Dispose();

static void DoOtherTasks()
{
    // Simulate other tasks being performed while OCR is in progress
    Console.WriteLine("Performing other tasks...");
    Thread.Sleep(2000); // Simulating work for 2000 milliseconds
}
Imports Microsoft.VisualBasic
Imports IronOcr

Private ocr As New IronTesseract()

Private largePdf As New OcrPdfInput("chapter1.pdf")

Private reader As Func(Of OcrResult) = Function()
	Return ocr.Read(largePdf)
End Function

Private readTask As New OcrReadTask(AddressOf reader.Invoke)
' Start the OCR task asynchronously
readTask.Start()

' Continue with other tasks while OCR is in progress
DoOtherTasks()

' Wait for the OCR task to complete and retrieve the result
Dim result As OcrResult = Await Task.Run(Function() readTask.Result)

Console.Write($"##### OCR RESULTS ###### " & vbLf & " {result.Text}")

largePdf.Dispose()
readTask.Dispose()

'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'static void DoOtherTasks()
'{
'	' Simulate other tasks being performed while OCR is in progress
'	Console.WriteLine("Performing other tasks...");
'	Thread.Sleep(2000); ' Simulating work for 2000 milliseconds
'}
$vbLabelText   $csharpLabel

Use Async Methods

ReadAsync() provides a straightforward and intuitive mechanism for initiating OCR operations asynchronously. Without the need for intricate threading or complex task management, developers can effortlessly integrate asynchronous OCR into their applications. This method liberates the main thread from the burdens of blocking OCR tasks, ensuring the application remains responsive and agile.

:path=/static-assets/ocr/content-code-examples/how-to/async-read-async.cs
using IronOcr;
using System;
using System.Threading.Tasks;

IronTesseract ocr = new IronTesseract();

using (OcrPdfInput largePdf = new OcrPdfInput("PDFs/example.pdf"))
{
    var result = await ocr.ReadAsync(largePdf);
    DoOtherTasks();
    Console.Write($"##### OCR RESULTS ###### " +
                $"\n {result.Text}");
}

static void DoOtherTasks()
{
    // Simulate other tasks being performed while OCR is in progress
    Console.WriteLine("Performing other tasks...");
    System.Threading.Thread.Sleep(2000); // Simulating work for 2000 milliseconds
}
Imports Microsoft.VisualBasic
Imports IronOcr
Imports System
Imports System.Threading.Tasks

Private ocr As New IronTesseract()

Using largePdf As New OcrPdfInput("PDFs/example.pdf")
	Dim result = Await ocr.ReadAsync(largePdf)
	DoOtherTasks()
	Console.Write($"##### OCR RESULTS ###### " & $vbLf & " {result.Text}")
End Using

'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'static void DoOtherTasks()
'{
'	' Simulate other tasks being performed while OCR is in progress
'	Console.WriteLine("Performing other tasks...");
'	System.Threading.Thread.Sleep(2000); ' Simulating work for 2000 milliseconds
'}
$vbLabelText   $csharpLabel

Conclusion

In summary, leveraging multithreading in IronOCR proves to be a game-changer for optimizing OCR tasks. The innate multithreading capabilities of IronOCR, combined with user-friendly methods like ReadAsync(), simplify the handling of large volumes of text data. This synergy ensures your applications remain responsive and efficient, making IronOCR a formidable tool for crafting high-performance software solutions with streamlined text recognition capabilities.

Preguntas Frecuentes

¿Cómo mejora la programación asincrónica las tareas de OCR?

La programación asincrónica en IronOCR permite que las tareas de OCR se ejecuten sin bloquear el hilo principal de la aplicación. Esto garantiza que la aplicación siga siendo receptiva mientras las operaciones de OCR se procesan en segundo plano.

¿Qué papel juega la multitarea en los procesos de OCR?

La multitarea en IronOCR permite el procesamiento paralelo en múltiples núcleos, optimizando los recursos del sistema y mejorando significativamente el rendimiento de las operaciones de reconocimiento de texto.

¿Cómo puedo comenzar a usar async y multitarea con Tesseract?

Para comenzar a usar async y multitarea con Tesseract, descargue una biblioteca de C# que admita estas características. IronOCR se integra sin problemas, permitiéndole gestionar las tareas de OCR eficientemente con métodos como ReadAsync().

¿Para qué se utiliza un objeto OcrReadTask?

Un objeto OcrReadTask en IronOCR encapsula operaciones de OCR, proporcionando a los desarrolladores un mayor control y flexibilidad para gestionar tareas de reconocimiento de texto de manera eficiente.

¿Cómo puedo realizar operaciones de OCR no bloqueantes?

Puede realizar operaciones de OCR no bloqueantes en IronOCR utilizando el método ReadAsync(). Este enfoque permite que las tareas de OCR se ejecuten asincrónicamente, liberando el hilo principal y manteniendo la aplicación receptiva.

¿Es posible procesar tanto PDFs como imágenes con IronOCR?

Sí, IronOCR puede procesar tanto PDFs como imágenes para el reconocimiento de texto. Utiliza capacidades de multitarea y asincronicidad para manejar eficientemente varios tipos de documentos.

¿Necesito una API especializada para implementar la multitarea en IronOCR?

No, no necesita una API especializada. IronOCR gestiona automáticamente la multitarea, aprovechando todos los núcleos disponibles para optimizar el rendimiento de las tareas de OCR.

¿Cómo beneficia el método ReadAsync() a las aplicaciones de OCR?

El método ReadAsync() en IronOCR permite a los desarrolladores iniciar operaciones de OCR de manera asincrónica, asegurando que las aplicaciones sigan siendo ágiles y receptivas incluso al procesar grandes volúmenes de datos de texto.

¿Cuáles son las ventajas de usar async y multitarea juntos en OCR?

Usar async y multitarea juntos en IronOCR proporciona una poderosa combinación para optimizar las tareas de OCR. Async garantiza una ejecución no bloqueante, mientras que la multitarea aprovecha múltiples núcleos para un procesamiento más rápido.

¿Puede IronOCR manejar automáticamente tareas de OCR en múltiples núcleos?

Sí, IronOCR utiliza automáticamente todos los núcleos disponibles para las tareas de OCR, optimizando la velocidad de procesamiento y la utilización de recursos sin requerir gestión explícita por parte del desarrollador.

¿IronOCR es totalmente compatible con .NET 10?

IronOCR es compatible con .NET 10 a través de su última versión 2025.11. Puede instalar la biblioteca mediante NuGet (Install-Package IronOcr) y ejecutar métodos asíncronos como ReadAsync() en .NET 10 sin necesidad de una configuración especial.

Chipego
Ingeniero de Software
Chipego tiene una habilidad natural para escuchar que le ayuda a comprender los problemas de los clientes y ofrecer soluciones inteligentes. Se unió al equipo de Iron Software en 2023, después de estudiar una Licenciatura en Ciencias en Tecnología de la Información. IronPDF e IronOCR son los dos ...
Leer más
¿Listo para empezar?
Nuget Descargas 5,044,537 | Versión: 2025.11 recién lanzado