How to Use Async and Multithread

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.


Get started with IronBarcode

Start using IronBarcode in your project today with a free trial.

First Step:
green 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.

Please noteTo 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.

Frequently Asked Questions

How can I implement asynchronous barcode reading in C#?

You can implement asynchronous barcode reading in C# by using IronBarcode's ReadAsync and ReadPdfAsync methods. These methods allow barcode reading from images and PDFs without blocking the main thread.

What are the steps to enable multithreading for barcode processing?

To enable multithreading for barcode processing, set the Multithreaded property to true and configure the MaxParallelThreads property to utilize multiple CPU cores efficiently. IronBarcode supports these configurations.

What are the advantages of using asynchronous operations in barcode reading?

Asynchronous operations in barcode reading allow tasks to proceed without blocking the main thread, enhancing application responsiveness, particularly in I/O-bound operations. IronBarcode's async methods facilitate this by using the async and await keywords.

How does multithreading improve barcode reading performance?

Multithreading improves barcode reading performance by allowing concurrent execution of tasks across multiple CPU cores, thus speeding up processing. This is particularly beneficial for CPU-bound tasks.

What is the default number of threads used in multithreaded barcode reading?

In IronBarcode, the default number of threads used for multithreaded barcode reading is 4, which can be adjusted via the MaxParallelThreads property based on your CPU's capabilities.

Where can I download the library for async and multithreaded barcode reading in C#?

You can download the library for async and multithreaded barcode reading in C# from the .NET package manager NuGet at https://nuget.org/packages/IronPdf/. This library provides functionalities for both async and multithreaded operations.

Can multithreading be used on all systems for barcode reading?

Multithreading can be used on systems with multiple CPU cores, as these cores enable concurrent processing of threads. IronBarcode's multithreading functionality takes advantage of such systems.

How can I compare the performance of normal, async, and multithreaded barcode reads?

The performance comparison shows that normal reads are the slowest, async reads are faster, and multithreaded reads are the fastest due to their utilization of multiple CPU cores. IronBarcode offers these reading options for enhanced performance.

What is the best method for reading multiple barcodes in a document?

IronBarcode provides comprehensive support for reading multiple barcodes in a document. For detailed guidance, refer to the documentation at /csharp/barcode/how-to/read-multiple-barcodes/.

Hairil Hasyimi Bin Omar
Software Engineer
Like all great engineers, Hairil is an avid learner. He’s refining his knowledge of C#, Python, and Java, using that knowledge to add value to team members across Iron Software. Hairil joined the Iron Software team from Universiti Teknologi MARA in Malaysia, where he graduated with a Bachelor's degree ...Read More