如何設置最大並行執行緒數量

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 方法讀取條碼圖片目錄,傳遞文件路徑和配置好的 BarcodeReaderOptions。 最後,通過存取 BarcodeResults 顯示條碼值和型別。

: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, optionsFaster);

    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, optionsFaster)

    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 以利用所有可用的執行緒。 在我們的案例中,我們使用一台擁有 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, optionsFaster);

    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 In pdfFiles
    ' Read the barcode
    Dim results = BarcodeReader.Read(file, optionsFaster)

    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 秒,比僅運行四個執行緒的速度快得多。 然而,請注意使用更多執行緒並不保證改善效能,因為這取決於主機處理器。 一般經驗法則是使用最大可用處理器減一,確保還有一個執行緒可用於其他系統操作。

警告 專案環境必須配置允許多執行緒。 否則,設置 Multithreadedtrue 並增加 MaxParallelThreads 並不會改善處理速度,甚至可能降低速度。

常見問題

在IronBarcode中設置最大平行執行緒的目的何在?

設置最大平行執行緒允許您通過高效使用系統資源來優化條碼生成性能,特別是在處理大量條碼時。

如何在IronBarcode中配置最大平行執行緒?

您可以在IronBarcode中通過在C#程式碼中使用適當的方法來設置條碼生成任務所需的執行緒數量。

為什麼優化大批量條碼建立的性能很重要?

優化大批量條碼建立性能確保過程高效快速,減少生成大量條碼所需的時間和資源,這對具有高吞吐量需求的應用程式至關重要。

在IronBarcode中使用平行處理有什麼好處?

IronBarcode中的平行處理允許使用多個CPU核心快速生成條碼,從而改進應用程式性能並縮短大規模條碼任務的處理時間。

設置過多的平行執行緒會對性能有負面影響嗎?

是的,設置過多的平行執行緒可能會導致資源競爭和增加的開銷,可能降低性能。重要的是找到與系統能力相匹配的平衡配置。

選擇平行執行緒數量時應考慮哪些因素?

考慮因素包括可用的CPU核心數量、系統的工作負載以及您的條碼生成任務的性質。最好嘗試不同的設置以找到最佳配置。

IronBarcode中是否有平行執行緒的預設設置?

IronBarcode可能有平行執行緒的預設設置,但建議根據您的特定應用需求自定義此設置以達到最佳性能。

IronBarcode如何處理執行緒管理?

IronBarcode利用.NET的執行緒功能來管理平行處理,允許開發者指定執行緒數量以有效優化性能。

我可以在執行期間動態更改平行執行緒的數量嗎?

在執行期間動態更改平行執行緒數量可能不建議,因為可能導致不一致並影響性能穩定性。最好在開始條碼生成過程之前設置配置。

在條碼生成中設置最大平行執行緒的一些常見用例是什麼?

常見用例包括需要高速條碼生成的應用程式,如庫存管理系統、零售銷售點系統和物流應用程式,這些應用程式需要快速處理大量條碼。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

準備好開始了嗎?
Nuget 下載 2,317,217 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

還在滾動嗎?

想快速驗證嗎? PM > Install-Package BarCode
運行範例觀看您的字串成為條碼。