How to Use Async and Multithread

by Hairil Hasyimi Bin Omar

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
VB   C#

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 note
To 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
VB   C#

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 ReadAsynchronous ReadMultithreaded Read (4 cores)
01.75 second01.67 second01.17 second

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.

Hairil related to Sample Image

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 in Chemical and Process Engineering.