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 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
$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

What is the difference between async and multithreading?

Async and multithreading both aim to enhance program performance by optimizing resource utilization. However, async allows operations to proceed without blocking the main thread, while multithreading divides tasks among multiple threads for concurrent execution.

How can asynchronous barcode reading be implemented in .NET applications?

Asynchronous barcode reading can be implemented using methods like `ReadAsync` and `ReadPdfAsync` which enable reading barcodes from images and PDFs without blocking the main thread. These methods are part of the IronBarcode library.

How do you enable multithreading for barcode reading?

Multithreading for barcode reading is enabled by setting appropriate properties to true and specifying the number of cores for concurrent execution. IronBarcode allows setting the `Multithreaded` property and using the `MaxParallelThreads` property for this purpose.

What are the benefits of using asynchronous operations?

Asynchronous operations allow long or blocking tasks to proceed without blocking the main thread, which frees the main thread to handle other tasks, improving application responsiveness, especially in I/O-bound operations.

What are the benefits of using multithreading?

Multithreading enhances application performance by allowing tasks to execute concurrently across multiple CPU cores, improving processing speed and efficiency for CPU-bound tasks.

How can I download the necessary library for async and multithread support?

You can download the C# library for async and multithread support from the .NET package manager NuGet at https://nuget.org/packages/IronPdf/. IronBarcode provides these functionalities.

What is the default value for MaxParallelThreads when implementing multithreading?

The default value for `MaxParallelThreads` in IronBarcode is 4, but it can be adjusted based on the available CPU cores.

How does the performance of normal, async, and multithreaded reads compare?

In performance comparisons, normal reads take longer than async and multithreaded reads. Async reads are slightly faster, and multithreaded reads, utilizing multiple cores, are the fastest.

Can multithreading be used on all machines?

Multithreading requires a machine with multiple CPU cores, as these cores independently execute the threads for concurrent processing.

Where can I find more information on reading multiple barcodes?

For more information on reading multiple barcodes with IronBarcode, visit the guide 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 in Chemical and Process Engineering.