如何設定最大並行執行緒數

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

在讀取大量BarCode時,若僅依賴單執行緒處理,可能會造成效能瓶頸並限制可擴展性。 然而,透過使用並行執行緒,您的應用程式便能同時處理多張圖片,有效倍增總處理效能,並大幅縮短完成批次工作的時間。

為這些執行緒設定最大限制,是優化效能的有效方法。 它透過在處理器核心間平衡工作負載,確保應用程式能充分發揮硬體的潛力。 此方法能最大化效率,在確保應用程式順暢運作的同時,提供最快的處理結果。

IronBarcode 提供了一種簡單的方法來控制此限制,確保機器能達到最佳效能。 以下章節將示範如何輕鬆設定這些執行緒限制。



設定最大並行執行緒數

在此範例中,我們將使用大量BarCode圖像,以說明採用多執行緒處理而非單執行緒處理所具備的可擴展性與效率。 您可在此處下載圖片資料夾。

若要設定 IronBarcode 使用多個執行緒,首先需建立一個新的 BarcodeReaderOptions 物件,並將 Multithreaded 設為 true。 隨後,透過賦予整數值來設定 MaxParallelThreads 屬性。 預設情況下,MaxParallelThreads 設定為 4。

完成設定後,系統會從資料夾中匯入大量BarCode影像。 接著,透過迴圈,使用 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

輸出

多執行緒輸出

如控制台輸出所示,它會顯示每張對應圖片的BarCode值與類型。

設定適當的最大並行執行緒數

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 秒。

處理時間與環境 ProcessorCount

32 處理器

如您所見,此操作的處理時間為 53 秒,這比僅使用四個執行緒執行時快得多。 但請注意,增加執行緒數量並不保證能提升效能,因為這取決於主機處理器的性能。 一般經驗法則為使用可用處理器數量減去一,以確保仍有單一執行緒可供其他系統操作使用。

警告 專案環境必須設定為允許多執行緒運作。 否則,將 Multithreaded 設為 true 並增加 MaxParallelThreads 並不會提升處理速度,甚至可能導致速度下降。)}]

常見問題

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

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

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

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

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

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

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

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

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

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

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

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

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

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

IronBarcode如何處理執行緒管理?

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

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

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

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

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

Curtis Chau
技術撰稿人

Curtis Chau 擁有卡爾頓大學(Carleton University)的電腦科學學士學位,專精於前端開發,並精通 Node.js、TypeScript、JavaScript 及 React。他熱衷於打造直觀且美觀的用戶介面,喜歡運用現代框架,並創建結構完善、視覺上吸引人的手冊。

除了開發工作之外,Curtis 對物聯網(IoT)抱有濃厚興趣,致力於探索整合硬體與軟體的創新方法。閒暇時,他喜歡玩遊戲和開發 Discord 機器人,將對科技的熱愛與創意相結合。

準備好開始了嗎?
Nuget 下載 2,240,258 | 版本: 2026.5 just released
Still Scrolling Icon

還在捲動嗎?

想要快速證明? PM > Install-Package BarCode
執行範例 看您的字串變成 BarCode。