How to Use Async and Multithread in C# with IronBarcode
Async and multithreading in IronBarcode optimize barcode reading performance differently - async prevents blocking the main thread during I/O operations while multithreading processes multiple barcodes simultaneously across CPU cores.
Developers often confuse Async and Multithreading operations. Both methods enhance program performance and efficiency by optimizing system resource utilization and reducing runtime. However, they differ in approach, mechanisms, and use cases. IronBarcode supports both approaches. This article explores their differences and implementation using IronBarcode.
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.
-
1Install IronBarcode with NuGet Package Manager
-
2Copy and run this code snippet.
var results = await IronBarCode.BarcodeReader.ReadAsync(imagePaths, new IronBarCode.BarcodeReaderOptions { Multithreaded = true, MaxParallelThreads = 4, ExpectMultipleBarcodes = true });C# -
3Deploy to test on your live environment
Start using IronBarcode in your project today with a free trial
Minimal Workflow (5 steps)
- Download the C# library for async and multithread support
- Use
ReadAsyncandReadPdfsAsyncmethods for asynchronous barcode reading from images and PDFs - Enable multithreading with the Multithreaded property set to 'true'
- Specify parallel thread count using the MaxParallelThreads property
- Check the performance comparison between normal, async, and multithreaded barcode reading
How Do I Read Barcodes Asynchronously with IronBarcode?
Asynchronous reading enables long or blocking operations to proceed without blocking the main thread's execution. In C#, use the async and await keywords with methods supporting asynchronous features. This approach doesn't create additional threads but releases the current thread. While the main thread initiates and manages tasks, it doesn't remain exclusively devoted to a single task. The main thread returns when the asynchronous method requires its involvement, freeing it to handle other tasks when not needed - particularly useful for I/O-bound tasks like reading/writing files or making network requests.
Consider barcode reading as an example. The process involves:
- Reading the file
- Applying reading options
- Decoding the barcode
During file reading, the main task can be released. This benefits scenarios with multiple image files or large PDFs, as demonstrated in our reading barcodes tutorial.
Use ReadAsync and ReadPdfsAsync methods to read barcodes asynchronously for images and PDF documents, respectively. Before implementing async operations, ensure you've installed IronBarcode via NuGet in your project.
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 resultThe code snippet above instantiates a List of image paths to be read asynchronously by IronBarcode. To read the images, use the ReadAsync method from the BarcodeReader class. Specify the imagePaths and reading options. For advanced configuration options, refer to our guide on barcode reader settings.
This asynchronous operation method is also available for reading barcodes in PDF documents through ReadPdfsAsync in the same class. For specific PDF reading configurations, see our PDF barcode reader settings guide.
Multithreaded
MaxParallelThreads
When Should I Use Async Reading Over Regular Methods?
Asynchronous reading excels in several scenarios:
- GUI Applications: Windows Forms or WPF applications requiring UI responsiveness. Async prevents interface freezing during barcode scanning.
- Web Applications: ASP.NET applications handling multiple concurrent requests without blocking threads, especially when processing uploaded barcode images.
- Batch Processing: Sequential reading of multiple barcode images or PDFs, allowing other tasks to execute during I/O operations.
- Network Operations: Reading barcodes from remote sources or URLs, as shown in our read barcodes from URL asynchronously example.
Why Does Async Reading Improve Application Responsiveness?
Asynchronous reading improves responsiveness by freeing the main thread during I/O-bound operations. When IronBarcode reads an image file from disk or processes a PDF, the thread doesn't wait idle. Instead, it handles other tasks like responding to user input or processing requests. This is especially noticeable when dealing with:
- Large image files requiring significant load time
- PDFs with multiple pages containing barcodes
- Network-based image sources
- Scenarios requiring image correction filters before barcode detection
What Are Common Pitfalls When Using Async Barcode Reading?
When implementing async barcode reading, watch for these common issues:
- Deadlocks: Avoid
ResultorWait()on async methods in UI contexts. Always useawaitthroughout the call chain. - Exception Handling: Wrap async calls in try-catch blocks as exceptions in async methods may not propagate as expected.
- Context Switching: Consider
ConfigureAwait(false)usage when you don't need to return to the original synchronization context. - Performance Misconceptions: Async doesn't accelerate individual operations; it improves application responsiveness. For speed improvements with multiple images, consider multithreading.
For troubleshooting async-related issues, consult our barcode recognition troubleshooting guide.
How Do I Enable Multithreaded Barcode Reading?
Unlike asynchronous operations, multithreading executes a single process across multiple threads simultaneously. Instead of sequential execution in a single thread, multithreading divides tasks among multiple threads for concurrent execution. Multithreading requires multiple CPU cores, as these cores independently execute threads. Like asynchronous operations, multithreading enhances application performance and responsiveness.
In IronBarcode, enable multithreading by setting the Multithreaded property and specifying maximum cores for concurrent execution using MaxParallelThreads in BarcodeReaderOptions. The default MaxParallelThreads value is 4, adjustable based on available CPU cores. For optimal performance configurations, see our reading speed options guide.
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 resultHow Much Performance Improvement Can I Expect?
Let's read two sample images and compare reading times across normal, asynchronous, and multithreaded operations.
Sample Image


| Normal Read | Asynchronous Read | Multithreaded Read (4 cores) |
|---|---|---|
| 01.75 seconds | 01.67 seconds | 01.17 seconds |
The comparison shows performance increases with asynchronous and multithreaded reading. In this illustrative example, multithreading provides a notable improvement over normal reading, while async delivers a smaller improvement; actual results vary by hardware, dataset, and IronBarcode version. However, these operations serve different purposes and approaches. Choose the approach that best suits your application requirements.
Performance improvements vary based on:
- Number of images processed
- Image complexity and barcode quality
- Available CPU cores
- Other system resources
For situations with multiple barcodes on a single document, visit the Read Multiple Barcodes guide.
When Should I Choose Multithreading Over Async Operations?
Choose multithreading when:
- CPU-Bound Operations: Processing involves heavy computation like complex image filters or high-resolution images
- Batch Processing: Multiple independent images require simultaneous processing
- Multi-Core Systems: Deployment environment has multiple CPU cores available
- Performance Critical: Raw processing speed outweighs resource efficiency
Choose async operations when:
- I/O-Bound Operations: Most time involves reading files or waiting for network responses
- UI Applications: Maintaining responsive user interfaces is crucial
- Limited Resources: Running on systems with limited CPU cores
- Web Applications: Handling multiple concurrent requests efficiently
How Do I Determine the Optimal MaxParallelThreads Value?
The optimal MaxParallelThreads value depends on several factors:
- Available CPU Cores: Start with
Environment.ProcessorCountas baseline - Workload Type: For pure barcode reading, use 75% of available cores
- System Resources: Leave headroom for OS and other processes
- Testing Results: Benchmark with your specific workload
Here's a practical approach to finding the optimal value:
int optimalThreads = Math.Max(1, Environment.ProcessorCount - 1);netFor production environments, monitor performance and adjust based on actual usage patterns. Consider implementing license key configuration for enterprise deployments requiring maximum performance.
For complete API capabilities, consult the IronBarcode API Reference.
Frequently Asked Questions
What is async barcode reading in C#?
Asynchronous barcode reading in C# with IronBarcode allows barcode scanning to proceed without blocking the main thread during I/O operations. This is useful for operations involving file reading or network requests. Methods like 'ReadAsync' in IronBarcode facilitate this by using 'async' and 'await' keywords.
How does multithreading improve barcode reading performance in IronBarcode?
Multithreading improves barcode reading performance by employing multiple threads to process images simultaneously across CPU cores. In IronBarcode, this feature is enabled by setting the 'Multithreaded' property and specifying 'MaxParallelThreads' in 'BarcodeReaderOptions'.
Can I use both async and multithreading for barcode reading in IronBarcode?
Yes, IronBarcode supports the combination of asynchronous reading and multithreading. This allows for efficient processing of multiple barcode images by utilizing async/await for non-blocking I/O and multithreading to leverage CPU cores for parallel processing.
When should I prefer async barcode reading over multithreaded operations?
Async reading should be preferred in scenarios where I/O-bound operations are predominant, such as reading files or managing network requests. It is also beneficial in applications where maintaining responsiveness, such as GUI and web applications, is crucial.
What are some common pitfalls when using async barcode reading?
Common pitfalls include deadlocks when using 'Result' or 'Wait' instead of 'await', insufficient exception handling, unnecessary context switching, and performance misconceptions where async is expected to accelerate individual operations.
What factors affect the optimal 'MaxParallelThreads' setting in IronBarcode?
The optimal 'MaxParallelThreads' value is influenced by available CPU cores, workload type, overall system resources, and testing results. A practical starting point is to use one less than the total available CPU cores.
How does IronBarcode's async functionality improve application responsiveness?
Async functionality in IronBarcode increases application responsiveness by freeing the main thread during long I/O-bound barcode reading tasks, allowing the application to handle other processes concurrently, such as user interface updates.
What are the advantages of using multithreading in barcode reading?
Multithreading allows simultaneous processing of multiple images, which enhances performance in CPU-bound operations such as processing complex image filters or high-resolution images. This is beneficial in environments with multiple CPU cores.
How can I implement license key configuration for optimal performance in IronBarcode?
For enterprise deployments requiring maximum performance, consider implementing license key configuration. This can be done by following IronBarcode's documentation on license key settings to fully unlock features and optimize resource utilization.
What are the key differences between async and multithreading in IronBarcode?
Async in IronBarcode prevents blocking the main thread during I/O operations, ideal for file and network tasks, whereas multithreading divides tasks among threads for concurrent execution across CPU cores, improving performance in CPU-bound operations.
