如何使用异步和多线程

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

海里海西米·賓·奧馬

這些條款 異步多執行緒 操作經常被混淆。這兩種方法旨在通過優化系統資源利用和減少運行時間來提高程序性能和效率。然而,它們在方法、機制和預期使用情況上有所不同。IronBarcode 支持這兩種方法。本文探討它們之間的差異以及如何使用 IronBarcode 實現它們。


C# NuGet 程式庫用于

安裝與 NuGet

Install-Package BarCode
Java PDF JAR

下載 DLL

下載DLL

手動安裝到您的項目中

C# NuGet 程式庫用于

安裝與 NuGet

Install-Package BarCode
Java PDF JAR

下載 DLL

下載DLL

手動安裝到您的項目中

立即開始在您的專案中使用IronPDF,並享受免費試用。

第一步:
green arrow pointer

查看 IronBarcodeNuget 快速安裝和部署。已被下載超過800萬次,它正用C#改變。

C# NuGet 程式庫用于 nuget.org/packages/BarCode/
Install-Package BarCode

請考慮安裝 IronBarcode DLL 直接下載並手動安裝到您的專案或GAC表單: IronBarCode.zip

手動安裝到您的項目中

下載DLL

異步讀取條碼範例

讓我們首先了解什麼是異步讀取及其對用戶的好處。異步讀取允許長時間運行或阻塞操作繼續進行,而不會阻止主執行緒的執行。在 C# 中,用戶可以利用 asyncawait 關鍵字來支持異步功能的方法。這不會創建額外的執行緒,而是釋放當前的執行緒。雖然還是需要主執行緒來啟動和管理任務,但它不需要專門用於單一任務。當異步方法需要其參與時,主執行緒會被召喚,當不需要時它可以處理其他任務——例如讀取/寫入文件或進行網絡請求等 I/O 邊界任務。

讓我們以條碼讀取為例。在這種情況下,涉及的步驟包括:

  • 讀取文件
  • 應用讀取選項
  • 解碼條碼

在“讀取文件”步驟中,主要任務可以被釋放。

使用 ReadAsyncReadPdfAsync 方法來分別異步讀取圖像和 PDF 文件中的條碼。

:path=/static-assets/barcode/content-code-examples/how-to/async-multithread-async.cs
using IronBarCode;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
#endregion
public class async_multithread_async
{
    public async Task codeAsync()
    {
        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

#End Region
Public Class async_multithread_async
	Public Async Function codeAsync() As Task
		Dim imagePaths As New List(Of String)() From {"image1.png", "image2.png"}

		' Barcode reading options
		Dim options As New BarcodeReaderOptions() With {.ExpectMultipleBarcodes = True}

		' Read barcode using Async
		Dim asyncResult As BarcodeResults = Await BarcodeReader.ReadAsync(imagePaths, options)

		' Print the results to console
		For Each result In asyncResult
			Console.WriteLine(result.ToString())
		Next result
VB   C#

從上面的程式碼片段中,我們已經實例化了一個圖像路徑列表,以便 IronBarcode 以異步方式讀取。要讀取圖像,您可以使用 BarcodeReader 類中的 ReadAsync 方法。用戶可以指定 imagePaths 以及讀取選項。

這種異步操作的方法也可用於讀取 PDF 文件中的條碼,稱為 ReadPdfAsync,它是同一類的一部分。

多线程读取条形码示例

與异步操作不同,多线程允许单一进程同时在多个线程中执行。这意味着与逐步在单一线程中执行进程不同,多线程将任务分配给多个线程,以实现同时执行。然而,要使多线程工作,机器必须具有多个CPU核心,这些核心用于独立执行线程。与异步操作类似,多线程旨在提高应用程序的性能和响应能力。

在IronBarcode中,通过设置Multithreaded属性并在BarcodeReaderOptions中使用MaxParallelThreads指定并发执行的最大核心数来启用多线程。MaxParallelThreads的默认值为4,可以根据可用的CPU核心数量进行调整。

請注意
要尋找可用的核心數:任務管理員 -> 性能標籤 -> 點擊CPU。'核心'欄位顯示數目。

:path=/static-assets/barcode/content-code-examples/how-to/async-multithread-multithread.cs
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 result
VB   C#

性能比較

現在,讓我們閱讀下方的兩張圖片,並比較正常、非同步和多執行緒操作的閱讀時間。

範例圖片

圖像 1
圖片2
正常讀取非同步讀取多线程读取(4 核心)
01.75 秒01.67 秒01.17 秒

從比較表可以明顯看出,一旦實現了異步和多線程讀取,性能會顯著提高。然而,這兩個操作的目的和方法不同。因此,使用者需要確定哪種方法更適合他們正在構建的應用程序。

最後,可能會出現單個文件上有多個條形碼的情況。了解更多信息,請訪問 讀取多個條碼 指南。

海里海西米·賓·奧馬

軟體工程師

和所有優秀的工程師一樣,Hairil 是一位熱衷學習的人。他正在精進自己對 C#、Python 和 Java 的知識,利用這些知識為 Iron Software 團隊的成員創造價值。Hairil 從馬來西亞的馬來西亞工藝大學加入了 Iron Software 團隊,他在那裡獲得了化學和過程工程學士學位。