如何设置最大并行线程数

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

读取大量条形码时,依赖单线程进程可能会造成性能瓶颈并限制可扩展性。 但是,使用并行线程可以让应用程序同时处理多个图像,从而有效地提高总处理能力,并大幅缩短完成批处理作业所需的时间。

为这些线程设置最大限制是优化性能的有效方法。 它通过在处理器核心之间平衡工作负载,确保应用程序充分利用硬件的潜力。 这种方法可以最大限度地提高效率,在保持应用程序流畅运行的同时,提供最快的结果。

IronBarcode 提供了一种简单的方法来控制此限制,从而确保实现最佳的机器性能。 以下部分演示如何轻松设置这些线程限制。



设置最大并行线程数

在这个例子中,我们将使用大量的条形码图像来说明使用多线程进程而不是单线程进程的可扩展性和效率。 您可以点击此处下载图片文件夹。

要配置 IronBarcode 以使用多个线程,首先需实例化一个新的 BarcodeReaderOptions 对象,并将 Multithreaded 设置为 true。 随后,通过赋值一个整数值来设置 MaxParallelThreads 属性。 默认情况下,MaxParallelThreads 设置为 4。

配置完成后,从文件夹中导入大量条形码图像。 随后,通过循环,使用 Read 方法读取 BARCODE 图像目录,并传入文件路径和已配置的 BarcodeReaderOptions。 最后,通过访问 BarcodeResults 可显示 BARCODE 的值和类型。

:path=/static-assets/barcode/content-code-examples/how-to/set-max-parallel-thread.cs
using Google.Protobuf.WellKnownTypes;
using IronBarCode;
using System;
using System.IO;

int maxParallelThreads = 4;


var optionsFaster = new BarcodeReaderOptions
{
    // Set Max threads to 4
    Multithreaded = true,
    MaxParallelThreads = maxParallelThreads,
};

// Dynamically get the "images" folder in the current directory
string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "images");

// Retrieve all JPG files in the directory
var pdfFiles = Directory.GetFiles(folderPath, "*.jpg");

foreach (var file in pdfFiles)
{
    // Read the barcode
    var results = BarcodeReader.Read(file);

    foreach (var result in results)
    {
        // Show the type and value for every barcode found
        Console.WriteLine($"Value: {result.Value}, Type: {result.BarcodeType}");

    }

}

Imports Google.Protobuf.WellKnownTypes
Imports IronBarCode
Imports System
Imports System.IO

Dim maxParallelThreads As Integer = 4

Dim optionsFaster As New BarcodeReaderOptions With {
    .Multithreaded = True,
    .MaxParallelThreads = maxParallelThreads
}

' Dynamically get the "images" folder in the current directory
Dim folderPath As String = Path.Combine(Directory.GetCurrentDirectory(), "images")

' Retrieve all JPG files in the directory
Dim pdfFiles = Directory.GetFiles(folderPath, "*.jpg")

For Each file In pdfFiles
    ' Read the barcode
    Dim results = BarcodeReader.Read(file)

    For Each result In results
        ' Show the type and value for every barcode found
        Console.WriteLine($"Value: {result.Value}, Type: {result.BarcodeType}")
    Next
Next
$vbLabelText   $csharpLabel

输出

多线程输出

如控制台输出所示,它会显示每个对应图像的条形码值和类型。

设置合适的最大并行线程数

Multithreaded 属性设置为 true 时,MaxParallelThreads 属性默认值为 4。尽管分配给 MaxParallelThreads 的整数没有硬性限制,但将该值设置为高于硬件逻辑核心容量,实际上可能会导致性能下降。 这是因为处理器无法处理过多的上下文切换,这可能会导致性能开销而不是速度提升。 因此,MaxParallelThreads 的正确值取决于计算机的具体配置,开发者应通过测试来确定适合其环境的最佳值。

在此示例中,我们将演示与上文相同的多线程场景,但会引入计时器,以对比默认值 4 与使用 Environment.ProcessorCount 调用所有可用线程的效果。 MaxParallelThreads 在本例中,我们使用的是配备 32 个逻辑处理器的计算机,因此 Environment.ProcessorCount 将设置为 32。

:path=/static-assets/barcode/content-code-examples/how-to/set-max-parallel-thread-performance.cs
using IronBarCode;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;

// Set the max parallel threads to the number of processor cores
int maxParallelThreads = Environment.ProcessorCount;


var optionsFaster = new BarcodeReaderOptions
{
    // Set Max threads to the number of processor cores
    Multithreaded = true,
    MaxParallelThreads = maxParallelThreads,
    ExpectMultipleBarcodes = true,
};

// Start timing the process
var stopwatch = Stopwatch.StartNew();
// Dynamically get the "images" folder in the current directory
string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "images");

// Check if directory exists to prevent crashes
if (!Directory.Exists(folderPath))
{
    Console.WriteLine($"Error: The directory '{folderPath}' does not exist.");
    return;
}

// Get all JPG files in the directory
var pdfFiles = Directory.GetFiles(folderPath, "*.jpg");

foreach (var file in pdfFiles)
{
    // Read the barcode
    var results = BarcodeReader.Read(file);

    if (results.Any())
    {
        Console.WriteLine($"Barcode(s) found in: {Path.GetFileName(file)}");
        foreach (var result in results)
        {
            Console.WriteLine($"  Value: {result.Value}, Type: {result.BarcodeType}");

        }
    }
}

stopwatch.Stop();

// Print number of images the barcode reader could decode
Console.WriteLine($" Max parallel threads of {maxParallelThreads} with {stopwatch.Elapsed.TotalSeconds:F2}s");
Imports IronBarCode
Imports System
Imports System.Diagnostics
Imports System.IO
Imports System.Linq

' Set the max parallel threads to the number of processor cores
Dim maxParallelThreads As Integer = Environment.ProcessorCount

Dim optionsFaster As New BarcodeReaderOptions With {
    .Multithreaded = True,
    .MaxParallelThreads = maxParallelThreads,
    .ExpectMultipleBarcodes = True
}

' Start timing the process
Dim stopwatch As Stopwatch = Stopwatch.StartNew()
' Dynamically get the "images" folder in the current directory
Dim folderPath As String = Path.Combine(Directory.GetCurrentDirectory(), "images")

' Check if directory exists to prevent crashes
If Not Directory.Exists(folderPath) Then
    Console.WriteLine($"Error: The directory '{folderPath}' does not exist.")
    Return
End If

' Get all JPG files in the directory
Dim pdfFiles As String() = Directory.GetFiles(folderPath, "*.jpg")

For Each file As String In pdfFiles
    ' Read the barcode
    Dim results = BarcodeReader.Read(file)

    If results.Any() Then
        Console.WriteLine($"Barcode(s) found in: {Path.GetFileName(file)}")
        For Each result In results
            Console.WriteLine($"  Value: {result.Value}, Type: {result.BarcodeType}")
        Next
    End If
Next

stopwatch.Stop()

' Print number of images the barcode reader could decode
Console.WriteLine($" Max parallel threads of {maxParallelThreads} with {stopwatch.Elapsed.TotalSeconds:F2}s")
$vbLabelText   $csharpLabel

输出

4线程处理时间

4 处理器

该过程的处理时间为 84 秒。

处理时间与环境处理器数量

32 处理器

如您所见,此操作的处理时间为 53 秒,这比仅使用四个线程运行它要快得多。 但是请注意,使用更多线程并不能保证性能提升,因为性能取决于主机处理器。 一般经验法则是使用可用处理器的最大数量减一,以确保仍然有一个线程可用于其他系统操作。

警告项目环境必须配置为允许多线程。 否则,将 Multithreaded 设置为 true 并增加 MaxParallelThreads 不仅无法提升处理速度,反而可能导致速度下降。)}]

常见问题解答

在 IronBarcode 中设置最大并行线程的目的是什么?

设置最大并行线程允许您通过有效利用系统资源来优化条形码生成的性能,尤其是在批量处理大量条形码时。

如何配置 IronBarcode 的最大并行线程数?

您可以通过在 C# 代码中使用适当的方法来配置 IronBarcode 的最大并行线程数,为条码生成任务设置所需的线程数。

为什么要优化批量创建 BarCode 的性能?

优化批量条形码创建的性能可确保流程高效快速,减少生成大量条形码所需的时间和资源,这对于具有高吞吐量需求的应用程序至关重要。

在 IronBarcode 中使用并行处理有什么好处?

IronBarcode 中的并行处理可通过利用多个 CPU 内核更快地生成条形码,从而提高应用程序性能并缩短大规模条形码任务的处理时间。

设置过多的并行线程会对性能产生负面影响吗?

是的,设置过多的并行线程会导致资源争用和开销增加,从而可能降低性能。重要的是要找到与系统能力相匹配的平衡配置。

在选择并行线程数量时应考虑哪些因素?

考虑因素包括可用 CPU 内核的数量、系统的工作量以及您的 BarCode 生成任务的性质。最好尝试不同的设置,以找到最佳配置。

IronBarcode 中是否有并行线程的默认设置?

IronBarcode 可能有并行线程的默认设置,但建议根据您的具体应用需求自定义此设置,以达到最佳性能。

IronBarcode 如何处理线程管理?

IronBarcode 利用 .NET 的线程功能管理并行处理,允许开发人员指定线程数量,以有效优化性能。

能否在执行过程中动态更改并行线程的数量?

不建议在执行过程中动态更改并行线程数,因为这会导致不一致并影响性能稳定性。最好在启动 BarCode 生成流程之前设置配置。

在条码生成中设置最大并行线程有哪些常见用例?

常见的使用案例包括需要高速生成 BarCode 的应用程序,如库存管理系统、零售点销售系统以及对快速处理大量条形码至关重要的物流应用程序。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。

准备开始了吗?
Nuget 下载 2,240,258 | 版本: 2026.5 just released
Still Scrolling Icon

还在滚动吗?

想快速获得证据? PM > Install-Package BarCode
运行示例 观看您的字符串变成 BarCode。