Cómo usar asincronicidad y multithreading en códigos de barras usando C#

How to Use Async and Multithread

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

The terms Async and Multithreading operations are often confused. Both methods aim to enhance program performance and efficiency by optimizing system resource utilization and reducing runtime. However, they differ in approach, mechanisms, and intended use cases. IronBarcode supports both approaches. This article explores the differences between them and how to implement them using IronBarcode.

Quickstart: Async & Multithreaded Barcode Reading Example

Use this one-line example to get started instantly with IronBarcode. It shows how easy it is to combine asynchronous reading and multithreading options to scan multiple barcode images in parallel with minimal setup.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronBarcode with NuGet Package Manager

    PM > Install-Package BarCode

  2. Copy and run this code snippet.

    var results = await IronBarCode.BarcodeReader.ReadAsync(imagePaths, new IronBarCode.BarcodeReaderOptions { Multithreaded = true, MaxParallelThreads = 4, ExpectMultipleBarcodes = true });
  3. Deploy to test on your live environment

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


Read Barcodes Asynchronously Example

Let's begin by understanding what asynchronous reading is and how it benefits users. Asynchronous reading enables long or blocking operations to proceed without blocking the main thread's execution. In C#, users can utilize the async and await keywords with methods supporting asynchronous features. This will not create additional threads, but instead, release the current thread. While the main thread is still necessary to initiate and manage tasks, it doesn't need to be exclusively devoted to a single task. The main thread is summoned when the asynchronous method requires its involvement, freeing it to handle other tasks when not needed—such as I/O-bound tasks like reading/writing files or making network requests.

Let's consider barcode reading as an example. In this scenario, the steps involved would be:

  • Reading the file
  • Applying reading options
  • Decoding the barcode

During the "Reading the file" step, the main task can be released.

Use the ReadAsync and ReadPdfAsync methods to read barcodes asynchronously for images and PDF documents, respectively.

:path=/static-assets/barcode/content-code-examples/how-to/async-multithread-async.cs
using IronBarCode;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

List<string> imagePaths = new List<string>() { "image1.png", "image2.png" };

// Barcode reading options
BarcodeReaderOptions options = new BarcodeReaderOptions()
{
    ExpectMultipleBarcodes = true
};

// Read barcode using Async
BarcodeResults asyncResult = await BarcodeReader.ReadAsync(imagePaths, options);

// Print the results to console
foreach (var result in asyncResult)
{
    Console.WriteLine(result.ToString());
}
Imports IronBarCode
Imports System
Imports System.Collections.Generic
Imports System.Threading.Tasks

Private imagePaths As New List(Of String)() From {"image1.png", "image2.png"}

' Barcode reading options
Private options As New BarcodeReaderOptions() With {.ExpectMultipleBarcodes = True}

' Read barcode using Async
Private asyncResult As BarcodeResults = await BarcodeReader.ReadAsync(imagePaths, options)

' Print the results to console
For Each result In asyncResult
	Console.WriteLine(result.ToString())
Next result
$vbLabelText   $csharpLabel

From the code snippet above, we have instantiated a List of image paths to be read asynchronously by IronBarcode. To read the images, you can use the ReadAsync method from the BarcodeReader class. Users can then specify the imagePaths as well as reading options.

This method for asynchronous operations is also available to read barcodes in PDF documents, known as ReadPdfAsync, which is part of the same class.

Read Barcodes in Multithread Example

Differing from asynchronous operations, multithreading allows a single process to be executed in multiple threads simultaneously. This means that instead of executing a process sequentially in a single thread, multithreading divides tasks among multiple threads, enabling concurrent execution. However, for multithreading to function, a machine must have multiple CPU cores, as these cores are used to independently execute the threads. Similar to asynchronous operations, multithreading aims to enhance the performance and responsiveness of applications.

In IronBarcode, enable multithreading by setting the Multithreaded property and specifying the maximum cores for concurrent execution using MaxParallelThreads in BarcodeReaderOptions. The default value for MaxParallelThreads is 4, which can be adjusted based on the available CPU cores.

Por favor notaTo find available cores: Task Manager -> Performance tab -> Click CPU. 'Cores' field displays count.

:path=/static-assets/barcode/content-code-examples/how-to/async-multithread-multithread.cs
using IronBarCode;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

List<string> imagePaths = new List<string>(){"test1.jpg", "test2.png"};

// Barcode reading options
BarcodeReaderOptions options = new BarcodeReaderOptions()
{
    Multithreaded = true,
    MaxParallelThreads = 4,
    ExpectMultipleBarcodes = true
};

// Read barcode with multithreaded enabled
BarcodeResults results = BarcodeReader.Read(imagePaths, options);

// Print the results to console
foreach (var result in results)
{
    Console.WriteLine(result.ToString());
}
Imports IronBarCode
Imports System
Imports System.Collections.Generic
Imports System.Threading.Tasks

Private imagePaths As New List(Of String)() From {"test1.jpg", "test2.png"}

' Barcode reading options
Private options As New BarcodeReaderOptions() With {
	.Multithreaded = True,
	.MaxParallelThreads = 4,
	.ExpectMultipleBarcodes = True
}

' Read barcode with multithreaded enabled
Private results As BarcodeResults = BarcodeReader.Read(imagePaths, options)

' Print the results to console
For Each result In results
	Console.WriteLine(result.ToString())
Next result
$vbLabelText   $csharpLabel

Performance Comparison

Now, let's read the two images below and compare the reading time of normal, asynchronous, and multithread operations.

Sample Image

Image 1
Image 2
Normal Read Asynchronous Read Multithreaded Read (4 cores)
01.75 seconds 01.67 seconds 01.17 seconds

From the comparison table, it's evident that there is a significant increase in performance once asynchronous and multithreaded reading is implemented. However, these two operations serve different purposes and approaches. Therefore, users need to determine which approach better suits the application they are building.

Finally, there might be situations where multiple barcodes are present on a single document. For more information, visit the Read Multiple Barcodes guide.

Preguntas Frecuentes

¿Cómo puedo implementar la lectura asincrónica de códigos de barras en C#?

Puedes implementar la lectura de códigos de barras asíncrona en C# utilizando los métodos ReadAsync y ReadPdfAsync de IronBarcode. Estos métodos permiten la lectura de códigos de barras desde imágenes y PDFs sin bloquear el hilo principal.

¿Cuáles son los pasos para habilitar el multihilo para el procesamiento de códigos de barras?

Para habilitar el procesamiento de códigos de barras en múltiples hilos, establece la propiedad Multithreaded en verdadero y configura la propiedad MaxParallelThreads para utilizar varios núcleos de CPU de manera eficiente. IronBarcode admite estas configuraciones.

¿Cuáles son las ventajas de usar operaciones asincrónicas en la lectura de códigos de barras?

Las operaciones asíncronas en la lectura de códigos de barras permiten que las tareas avancen sin bloquear el hilo principal, mejorando la capacidad de respuesta de la aplicación, particularmente en operaciones dependientes de I/O. Los métodos asíncronos de IronBarcode facilitan esto utilizando las palabras clave async y await.

¿Cómo mejora el rendimiento del multihilo en la lectura de códigos de barras?

El multihilo mejora el rendimiento de la lectura de códigos de barras permitiendo la ejecución concurrente de tareas en múltiples núcleos de CPU, acelerando así el procesamiento. Esto es particularmente beneficioso para tareas que dependen del CPU.

¿Cuál es el número predeterminado de hilos usados en la lectura multihilo de códigos de barras?

En IronBarcode, el número predeterminado de hilos utilizados para la lectura de códigos de barras multihilo es 4, que se puede ajustar a través de la propiedad MaxParallelThreads según las capacidades de su CPU.

¿Dónde puedo descargar la biblioteca para la lectura asincrónica y multihilo de códigos de barras en C#?

Puedes descargar la biblioteca para la lectura asincrónica y multihilo de códigos de barras en C# desde el gestor de paquetes de .NET NuGet en https://nuget.org/packages/IronPdf/. Esta biblioteca proporciona funcionalidades para operaciones tanto asincrónicas como multihilo.

¿Se puede usar el multihilo en todos los sistemas para la lectura de códigos de barras?

El multihilo puede ser utilizado en sistemas con múltiples núcleos de CPU, ya que estos núcleos permiten el procesamiento concurrente de hilos. La funcionalidad de multihilo de IronBarcode aprovecha dichos sistemas.

¿Cómo puedo comparar el rendimiento de las lecturas normales, asincrónicas y multihilo de códigos de barras?

La comparación de rendimiento muestra que las lecturas normales son las más lentas, las lecturas asincrónicas son más rápidas y las lecturas multihilo son las más rápidas debido a su utilización de múltiples núcleos de CPU. IronBarcode ofrece estas opciones de lectura para un rendimiento mejorado.

¿Cuál es el mejor método para leer múltiples códigos de barras en un documento?

IronBarcode proporciona un soporte completo para la lectura de múltiples códigos de barras en un documento. Para obtener una guía detallada, consulta la documentación en /csharp/barcode/how-to/read-multiple-barcodes/.

Hairil Hasyimi Bin Omar
Ingeniero de Software
Como todos los grandes ingenieros, Hairil es un ávido aprendiz. Está refinando su conocimiento de C#, Python y Java, usando ese conocimiento para agregar valor a los miembros del equipo en Iron Software. Hairil se unió al equipo de Iron Software desde la Universiti Teknologi MARA en Malasia, donde se ...
Leer más
¿Listo para empezar?
Nuget Descargas 1,935,276 | Versión: 2025.11 recién lanzado