如何在C#中使用Async和多執行緒與IronBarcode
IronBarcode中的Async和多執行緒以不同的方式優化條碼讀取性能 - async防止在I/O操作中阻塞主線程而多執行緒跨CPU核心同時處理多個條碼。
開發者經常混淆Async和Multithreading操作。 這兩種方法都能透過最佳化系統資源利用率和縮短執行時間來提升程式效能和效率。然而,它們在方法、機制和使用案例上有所不同。 IronBarcode 兩種方法都支援。 本文將探討它們的差異以及使用 IronBarcode 的實作。
使用以下一行範例即可立即開始使用 IronBarcode。 它展示瞭如何輕鬆地將非同步讀取和多線程選項結合起來,以最少的設定並行掃描多個條碼圖像。
-
1使用 IronBarcode 安裝 NuGet Package Manager
-
2複製並運行這段程式碼。
var results = await IronBarCode.BarcodeReader.ReadAsync(imagePaths, new IronBarCode.BarcodeReaderOptions { Multithreaded = true, MaxParallelThreads = 4, ExpectMultipleBarcodes = true });Dim results = Await IronBarCode.BarcodeReader.ReadAsync(imagePaths, New IronBarCode.BarcodeReaderOptions With {.Multithreaded = True, .MaxParallelThreads = 4, .ExpectMultipleBarcodes = True})Dim results = Await IronBarCode.BarcodeReader.ReadAsync(imagePaths, New IronBarCode.BarcodeReaderOptions With {.Multithreaded = True, .MaxParallelThreads = 4, .ExpectMultipleBarcodes = True}) -
3部署到您的生產環境進行測試
立即在您的項目中開始使用 IronBarcode,並使用 免費試用
最小工作流程(5 個步驟)
- 下載支援非同步和多執行緒的C#程式庫
- 使用
ReadAsync和ReadPdfsAsync方法從圖像和PDF中非同步讀取條碼 - 將Multithreaded屬性設為「true」即可啟用多執行緒。
- 使用MaxParallelThreads屬性指定並行執行緒數
- 檢查正常、異步和多線程條碼讀取之間的性能比較
如何使用IronBarcode非同步地讀取條碼?
非同步讀取允許長時間或阻塞性操作在不阻塞主執行緒執行的情況下進行。 在C#中,使用async和await關鍵字來支援非同步特性的函式。 此方法不會建立額外的線程,而是釋放目前的線程。 主線程會啟動和管理任務,但不會只專注於單一任務。 當非同步方法需要主線程參與時,主線程返回,從而在不需要時釋放它來處理其他任務,這對於I/O綁定任務如讀/寫文件或進行網路請求特別有用。
以 BarCode 讀取為例。 過程包括
- 讀取文件
- 應用閱讀選項
- 解碼條碼
在閱讀檔案的過程中,主要任務可以釋放。 這對多個圖像文件或大型PDF的場景有益,如我們的條碼讀取教程中所示。
分別使用ReadAsync和ReadPdfsAsync方法來非同步地讀取圖片和PDF文件的條碼。 在實施非同步操作之前,確保您已在專案中通過NuGet安裝了IronBarcode。
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());
}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 resultImports 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上面的代碼片段實例化了一個List圖像路徑,將由IronBarcode非同步讀取。 要讀取圖片,使用ReadAsync方法從BarcodeReader類別。 指定imagePaths和讀取選項。 如需高級配置選項,請參閱我們的條碼讀取器設置指南。
這個非同步操作方法也可以用於通過ReadPdfsAsync在相同類別中讀取PDF文件中的條碼。 如需特定的PDF讀取配置,請參閱我們的PDF條碼讀取器設置指南。
Multithreaded
MaxParallelThreads
什麼時候應該使用非同步讀取而不是常規方法?
異步閱讀在幾種情況下表現優異:
- GUI應用程式:需要UI響應的Windows Forms或WPF應用程式。 Async 可防止條碼掃描時介面凍結。
- Web應用程式:ASP.NET應用程式處理多個並發請求而不阻塞線程,特別是在處理上傳的條碼圖像時。
- 批次處理:順序讀取多個條碼圖像或PDF,允許其他任務在I/O操作期間執行。
- 網路操作:從遠程來源或URL讀取條碼,如我們的非同步從URL讀取條碼示例中所示。
為什麼非同步讀取能提高應用程式的響應性?
異步讀取透過在 I/O 綁定作業期間釋放主線程來改善反應速度。 當 IronBarcode 從磁碟讀取影像檔案或處理 PDF 時,線程不會空閒等待。 而不是處理其他工作,例如回應使用者輸入或處理請求。 這一點在處理以下項目時尤其明顯:
- 需要大量載入時間的大型圖檔
- 包含 BarCode 的多頁 PDF 檔案
- 基於網路的影像來源
- 需要在條碼檢測之前進行圖像校正濾鏡的場景
使用非同步條碼讀取時有哪些常見陷阱?
在實施 async BarCode 讀取時,請注意這些常見問題:
- 死結:避免在UI環境中對非同步方法使用
Result或Wait()。 始終在調用鏈中使用await。 - 異常處理:在try-catch塊中包裝非同步調用,因為非同步方法中的異常可能不會如預期地傳播。
- 上下文切換:當不需要返回原始同步上下文時,考慮使用
ConfigureAwait(false)。 - 性能誤解:非同步不會加速單個操作; 可提高應用程式的反應能力。 若要提高多張圖片的速度,請考慮使用多執行緒。
如需解決非同步相關問題,請參閱我們的條碼識別故障排除指南。
如何啟用多執行緒條碼讀取?
與非同步操作不同,多執行緒會同時在多個線程上執行單一程序。 多執行緒(multithreading)並非在單一線程中順序執行,而是將任務分給多個線程同時執行。 多執行緒需要多個 CPU 核心,因為這些核心會獨立執行執行緒。 與異步作業一樣,多執行緒可增強應用程式的效能與反應能力。
在IronBarcode中,通過設定Multithreaded屬性啟用多執行緒,並使用MaxParallelThreads在BarcodeReaderOptions中指定同時運行的最大核心數。 預設的MaxParallelThreads值為4,可根據可用CPU核心數進行調整。 如需最佳性能配置,請參閱我們的讀取速度選項指南。
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());
}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 resultImports 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可以期待多大程度的性能提升?
讓我們來讀取兩個範例圖片,並比較正常、非同步和多執行緒操作的讀取時間。
樣本圖像


| 正常閱讀 | 非同步讀取 | 多線程讀取(4 核) |
|---|---|---|
| 1.75秒 | 1.67秒 | 1.17秒 |
比較表明非同步和多執行緒讀取時的性能提升。 在這個說明性例子中,多執行緒較普通讀取提供顯著提升,而非同步提供較小的提升; 實際結果會因硬體、數據集和IronBarcode版本而異。 然而,這些作業的目的和方式各不相同。 選擇最適合您應用需求的方式。
效能改善依下列因素而異:
- 處理的圖片數量
- 影像複雜度與 BarCode 品質
- 可用的 CPU 核心
- 其他系統資源
對於單個文件上的多個條碼情況,請訪問讀取多個條碼指南。
什麼時候應該選擇多執行緒而不是非同步操作?
選擇多執行緒時:
- CPU密集型操作:處理涉及大型計算,如複雜的圖像濾鏡或高解析度圖像
- 批次處理:需要同時處理多個獨立的圖像
- 多核心系統:部署環境擁有多個可用的CPU核心
- 性能至關重要:原始處理速度重於資源效率
在下列情況下選擇非同步作業
- I/O密集型操作:大部分時間涉及讀取文件或等待網路響應
- UI應用程式:保持使用者界面響應至關重要
- 資源有限:在CPU核心有限的系統上運行
- Web應用程式:處理多個並發請求效率高
如何確定最佳的MaxParallelThreads值?
最佳的MaxParallelThreads值取決於幾個因素:
- 可用的CPU核心:以
Environment.ProcessorCount作為基準開始 - 工作負載類型:對於純條碼讀取,使用可用核心的75%
- 系統資源:為操作系統和其他進程留出空間
- 測試結果:根據您的特定工作負載進行基準測試
以下是尋找最佳值的實用方法:
int optimalThreads = Math.Max(1, Environment.ProcessorCount - 1);int optimalThreads = Math.Max(1, Environment.ProcessorCount - 1);netnet對於生產環境,請監控效能,並根據實際使用模式進行調整。 考慮實施授權金鑰配置以滿足企業部署的最高性能需求。
如需完整的API功能,請參閱IronBarcode API參考。
常見問題
什麼是C#中的異步條碼讀取?
使用IronBarcode在C#中進行異步條碼讀取允許條碼掃描在I/O操作期間不阻塞主執行緒。這對於涉及檔案讀取或網路請求的操作非常有用。IronBarcode中的'ReadAsync'等方法通過使用'async'和'await'關鍵字來實現這一點。
多執行緒如何提高IronBarcode中的條碼讀取效能?
多執行緒通過使用多個執行緒同時處理跨CPU核心的圖像來提高條碼讀取效能。在IronBarcode中,可以通過設定'Multithreaded'屬性並在'BarcodeReaderOptions'中指定'MaxParallelThreads'來開啟此功能。
我能在IronBarcode中同時使用異步和多執行緒進行條碼讀取嗎?
是的,IronBarcode支持異步讀取和多執行緒的組合。這允許利用async/await進行非阻塞的I/O以及多執行緒利用CPU核心的平行處理來有效處理多個條碼圖像。
什麼時候應該優先考慮異步條碼讀取而不是多執行緒操作?
在以I/O為主的場景中,例如讀取檔案或管理網絡請求,應優先考慮異步讀取。在需要保持響應性的應用中,例如GUI和網絡應用,也非常有益。
使用異步條碼讀取時常見的陷阱是什麼?
常見的陷阱包括使用'Result'或'Wait'而不是'await'導致的死鎖、不足的例外處理、不必要的上下文切換,及對異步會加速單個操作的錯誤認識。
哪些因素會影響IronBarcode中最佳的'MaxParallelThreads'設置?
最佳'MaxParallelThreads'值受可用CPU核心、工作負載類型、整體系統資源和測試結果影響。實際的起點是使用比總可用CPU核心少一個。
IronBarcode的異步功能如何提高應用程式響應能力?
IronBarcode中的異步功能通過在長時間I/O為主的條碼讀取任務中釋放主執行緒,來提高應用程式的響應能力,使應用程式能同時處理其他進程,如用戶介面更新。
在條碼讀取中使用多執行緒的優勢是什麼?
多執行緒能同時處理多個圖像,增強在CPU為主的操作中的效能,如處理複雜的圖像過濾器或高解析度圖像。在擁有多個CPU核心的環境中非常有益。
如何在IronBarcode中實現授權密鑰配置以獲得最佳效能?
對於需要最大效能的企業部署,請考慮實施授權密鑰配置。可以按照IronBarcode的授權密鑰設置文檔進行操作,以充分解鎖功能並優化資源利用。
IronBarcode中的異步和多執行緒有什麼主要區別?
IronBarcode中的異步功能在I/O操作期間防止阻塞主執行緒,非常適合檔案和網絡任務,而多執行緒則將任務劃分為多個執行緒,以便在CPU核心中同時執行,提高在CPU為主的操作中的效能。