C# 異步與多線程支持,搭配IronOCR
IronOCR自動處理所有CPU核心的多線程,並提供像ReadAsync()這樣的異步方法,以在不阻塞主線程的情況下進行OCR,確保在處理大型文件時應用程式保持響應。 對於記憶體限制的工作負載,MaxDegreeOfParallelism 和 MultiThreaded 屬性在 IronTesseract 上限制一次讀取的頁數。
介紹
有效處理大量文本數據需要準確性和速度,以進行OCR操作。 本文涵蓋 IronOCR 和 Tesseract 的同步支援和多執行緒。 異步程式設計可讓 OCR 執行不阻塞,讓應用程式在執行文字辨識任務時保持反應迅速。 多執行緒提供平行性,大幅提升 OCR 效能。 這些技術可協助開發人員提高 OCR 驅動應用程式的效率和回應能力。
快速入門:使用ReadAsync 進行輕鬆的異步OCR
使用 IronTesseract 的 ReadAsync 方法來執行不會阻塞主線程的OCR。 此功能可快速為您的應用程式加入反應迅速、無阻塞的 OCR 功能。 這在處理PDF文件或同時處理多個圖像文件時效果特別好。
-
1使用 IronOCR 安裝 NuGet Package Manager
-
2複製並運行這段程式碼。
var result = await new IronOcr.IronTesseract().ReadAsync("image.png");Dim result = Await New IronOcr.IronTesseract().ReadAsync("image.png")Dim result = Await New IronOcr.IronTesseract().ReadAsync("image.png") -
3部署到您的生產環境進行測試
立即在您的項目中開始使用 IronOCR,並使用 免費試用
最小工作流程(5 個步驟)
- 下載支持Tesseract的C#程式庫,具有異步和多線程功能
- 利用 IronOCR 管理的多線程
- 准備 PDF 文檔和圖像以供閱讀
- 使用
OcrReadTask物件來利用異步並發的優勢 - 為了方便起見,請使用
ReadAsync方法
IronOCR中的多線程如何工作?
IronOCR通過流暢的多線程增強圖像處理和OCR讀取效率,無需開發人員使用專門的API即可開始使用。 IronTesseract默認情況下自動利用所有可用的多核心線程,優化系統資源以快速執行OCR。 此內建的多執行緒可將平行性直接整合至 OCR 工作流程中,進而簡化開發工作並大幅提升效能。 當您需要限制這種並行性時 - 例如在內存限制的容器或共享主機上 - 請參閱下文有關控制並行性和內存使用的部分。
程式庫的多線程Tesseract實現提供以下主要優勢:
- **自動CPU核心利用: ** IronOCR檢測並使用所有可用核心而無需手動配置,當您需要時,可以使用
MaxDegreeOfParallelism進行限制 - **線程安全操作: ** OCR操作是線程安全的,單一
IronTesseract實例可以安全地在並行讀取中共享 - **可調內存佔用: ** 每頁並行讀取使用其自己的Tesseract引擎,因此最高內存隨著並行程度而變化 - 降低佔用以換取較小的工作集吞吐量
- **可擴展性能: ** 處理時間隨可用核心數量成比例減少
以下是一個 C# 語言的多執行緒讀取範例:
using IronOcr;
using System;
var ocr = new IronTesseract();
using (var input = new OcrPdfInput(@"example.pdf"))
{
var result = ocr.Read(input);
Console.WriteLine(result.Text);
};using IronOcr;
using System;
var ocr = new IronTesseract();
using (var input = new OcrPdfInput(@"example.pdf"))
{
var result = ocr.Read(input);
Console.WriteLine(result.Text);
};Imports IronOcr
Imports System
Private ocr = New IronTesseract()
Using input = New OcrPdfInput("example.pdf")
Dim result = ocr.Read(input)
Console.WriteLine(result.Text)
End UsingImports IronOcr
Imports System
Private ocr = New IronTesseract()
Using input = New OcrPdfInput("example.pdf")
Dim result = ocr.Read(input)
Console.WriteLine(result.Text)
End Using在IronTesseract上有兩個屬性可讓您微調此行為以滿足特定的性能和內存要求,會在下一節中討論。 關於不同的優化方向 - 為了速度而略微犧牲準確性 - 請參閱快速OCR配置。
如何控制並行性和內存使用?
默認情況下,IronTesseract與機器上的CPU核心數相當,並行讀取多個頁面,每個並行頁面運行其本身的Tesseract引擎。當內存比吞吐量更重要時,有兩個屬性可讓您限制這點:
MaxDegreeOfParallelism限制單個Read調用中同時OCR處理的頁數。 因為每個並行頁面都需要一個引擎,降低它直接降低最高內存。MultiThreaded在設置為false時,完全關閉並行讀取,提供最低且最可預測的資源佔用。 它優先於MaxDegreeOfParallelism。
using IronOcr;
var ocr = new IronTesseract
{
Language = OcrLanguage.English,
MaxDegreeOfParallelism = 2 // OCR at most 2 pages at once per Read
};
using var input = new OcrInput();
input.LoadPdf("invoice.pdf");
var result = ocr.Read(input);using IronOcr;
var ocr = new IronTesseract
{
Language = OcrLanguage.English,
MaxDegreeOfParallelism = 2 // OCR at most 2 pages at once per Read
};
using var input = new OcrInput();
input.LoadPdf("invoice.pdf");
var result = ocr.Read(input);Imports IronOcr
Dim ocr = New IronTesseract With {
.Language = OcrLanguage.English,
.MaxDegreeOfParallelism = 2 ' OCR at most 2 pages at once per Read
}
Using input = New OcrInput()
input.LoadPdf("invoice.pdf")
Dim result = ocr.Read(input)
End UsingImports IronOcr
Dim ocr = New IronTesseract With {
.Language = OcrLanguage.English,
.MaxDegreeOfParallelism = 2 ' OCR at most 2 pages at once per Read
}
Using input = New OcrInput()
input.LoadPdf("invoice.pdf")
Dim result = ocr.Read(input)
End UsingMultiThreaded 在早期版本中無效 - 現在它是一個即時設置。 設置MultiThreaded = false的程式碼在升級後將順序讀取,沒有編譯器警告也沒有異常。Read 呼叫中限制了並行性。 跨多個文件或多個Read呼叫的併發仍然是您的應用程式的責任 - 與下面的異步模式結合。有關默認值、兩個屬性之間的優先規則、選擇值的指導以及在高容量並行OCR中解決的AccessViolationException細節,請參閱如何限制並行OCR的內存使用。
如何在IronOCR中使用異步支持?
異步程式設計可讓開發人員在不阻塞主線程的情況下執行 OCR 任務,從而優化 OCR 的效能。 這可讓應用程式在處理大型文件或影像以進行文字辨識時保持反應迅速。 Async 支援可讓系統在背景執行 OCR 作業時處理其他任務。 這項功能在實施OCR進度跟蹤在用戶介面時至關重要。
本節涵蓋 IronOCR 中的 async 支援整合,示範讓 OCR 服務非阻塞的不同方法。 IronOCR 的 async 功能可確保桌面應用程式在執行 OCR 作業時的回應能力,以及處理多個並發 OCR 請求的 Web 服務,都能達到最佳效能。
什麼時候應該使用OcrReadTask對象?
OcrReadTask對象提升了IronOCR中的OCR流程控制和靈活性。 這些物件封裝了 OCR 作業,可有效管理文字辨識任務。 此部份展示了如何在您的IronOCR工作流程中使用OcrReadTask對象,並顯示它們如何啟動和優化OCR任務。 OcrReadTask對象在協調複雜的文件處理或微調應用程式響應能力時有助於最大化IronOCR的功能。
OcrReadTask對象在以下情況下效果最佳:
- 您需要對任務執行進行細粒度控制
- 實施中止標記功能以進行可取消操作
- 管理具有不同優先順序的多個並行 OCR 作業
- 與自訂任務排程器或工作流程引擎整合
using IronOcr;
IronTesseract ocr = new IronTesseract();
OcrPdfInput largePdf = new OcrPdfInput("chapter1.pdf");
Func<OcrResult> reader = () =>
{
return ocr.Read(largePdf);
};
OcrReadTask readTask = new OcrReadTask(reader.Invoke);
// Start the OCR task asynchronously
readTask.Start();
// Continue with other tasks while OCR is in progress
DoOtherTasks();
// Wait for the OCR task to complete and retrieve the result
OcrResult result = await Task.Run(() => readTask.Result);
Console.Write($"##### OCR RESULTS ###### \n {result.Text}");
largePdf.Dispose();
readTask.Dispose();
static void DoOtherTasks()
{
// Simulate other tasks being performed while OCR is in progress
Console.WriteLine("Performing other tasks...");
Thread.Sleep(2000); // Simulating work for 2000 milliseconds
}using IronOcr;
IronTesseract ocr = new IronTesseract();
OcrPdfInput largePdf = new OcrPdfInput("chapter1.pdf");
Func<OcrResult> reader = () =>
{
return ocr.Read(largePdf);
};
OcrReadTask readTask = new OcrReadTask(reader.Invoke);
// Start the OCR task asynchronously
readTask.Start();
// Continue with other tasks while OCR is in progress
DoOtherTasks();
// Wait for the OCR task to complete and retrieve the result
OcrResult result = await Task.Run(() => readTask.Result);
Console.Write($"##### OCR RESULTS ###### \n {result.Text}");
largePdf.Dispose();
readTask.Dispose();
static void DoOtherTasks()
{
// Simulate other tasks being performed while OCR is in progress
Console.WriteLine("Performing other tasks...");
Thread.Sleep(2000); // Simulating work for 2000 milliseconds
}Imports Microsoft.VisualBasic
Imports IronOcr
Private ocr As New IronTesseract()
Private largePdf As New OcrPdfInput("chapter1.pdf")
Private reader As Func(Of OcrResult) = Function()
Return ocr.Read(largePdf)
End Function
Private readTask As New OcrReadTask(AddressOf reader.Invoke)
' Start the OCR task asynchronously
readTask.Start()
' Continue with other tasks while OCR is in progress
DoOtherTasks()
' Wait for the OCR task to complete and retrieve the result
Dim result As OcrResult = Await Task.Run(Function() readTask.Result)
Console.Write($"##### OCR RESULTS ###### " & vbLf & " {result.Text}")
largePdf.Dispose()
readTask.Dispose()
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'static void DoOtherTasks()
'{
' ' Simulate other tasks being performed while OCR is in progress
' Console.WriteLine("Performing other tasks...");
' Thread.Sleep(2000); ' Simulating work for 2000 milliseconds
'}Imports Microsoft.VisualBasic
Imports IronOcr
Private ocr As New IronTesseract()
Private largePdf As New OcrPdfInput("chapter1.pdf")
Private reader As Func(Of OcrResult) = Function()
Return ocr.Read(largePdf)
End Function
Private readTask As New OcrReadTask(AddressOf reader.Invoke)
' Start the OCR task asynchronously
readTask.Start()
' Continue with other tasks while OCR is in progress
DoOtherTasks()
' Wait for the OCR task to complete and retrieve the result
Dim result As OcrResult = Await Task.Run(Function() readTask.Result)
Console.Write($"##### OCR RESULTS ###### " & vbLf & " {result.Text}")
largePdf.Dispose()
readTask.Dispose()
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'static void DoOtherTasks()
'{
' ' Simulate other tasks being performed while OCR is in progress
' Console.WriteLine("Performing other tasks...");
' Thread.Sleep(2000); ' Simulating work for 2000 milliseconds
'}如何使用ReadAsync方法?
ReadAsync()提供了一種異步啟動OCR操作的直接機制。 不需要複雜的線程或任務管理,開發人員就可以將異步 OCR 整合到他們的應用程式中。 此方法可防止主線程在執行 OCR 任務時阻塞,確保應用程式保持反應迅速。
ReadAsync方法在以下情況下效果良好:
- 需要維持 UI 反應能力的桌面應用程式
- 處理多個同步 OCR 請求的網路應用程式
- 批次處理場景, 進度跟蹤至關重要
- 與 .NET 應用程式中的現代 async/await 模式整合
using IronOcr;
using System;
using System.Threading.Tasks;
IronTesseract ocr = new IronTesseract();
using (OcrPdfInput largePdf = new OcrPdfInput("PDFs/example.pdf"))
{
var result = await ocr.ReadAsync(largePdf);
DoOtherTasks();
Console.Write($"##### OCR RESULTS ###### " +
$"\n {result.Text}");
}
static void DoOtherTasks()
{
// Simulate other tasks being performed while OCR is in progress
Console.WriteLine("Performing other tasks...");
System.Threading.Thread.Sleep(2000); // Simulating work for 2000 milliseconds
}using IronOcr;
using System;
using System.Threading.Tasks;
IronTesseract ocr = new IronTesseract();
using (OcrPdfInput largePdf = new OcrPdfInput("PDFs/example.pdf"))
{
var result = await ocr.ReadAsync(largePdf);
DoOtherTasks();
Console.Write($"##### OCR RESULTS ###### " +
$"\n {result.Text}");
}
static void DoOtherTasks()
{
// Simulate other tasks being performed while OCR is in progress
Console.WriteLine("Performing other tasks...");
System.Threading.Thread.Sleep(2000); // Simulating work for 2000 milliseconds
}Imports Microsoft.VisualBasic
Imports IronOcr
Imports System
Imports System.Threading.Tasks
Private ocr As New IronTesseract()
Using largePdf As New OcrPdfInput("PDFs/example.pdf")
Dim result = Await ocr.ReadAsync(largePdf)
DoOtherTasks()
Console.Write($"##### OCR RESULTS ###### " & $vbLf & " {result.Text}")
End Using
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'static void DoOtherTasks()
'{
' ' Simulate other tasks being performed while OCR is in progress
' Console.WriteLine("Performing other tasks...");
' System.Threading.Thread.Sleep(2000); ' Simulating work for 2000 milliseconds
'}Imports Microsoft.VisualBasic
Imports IronOcr
Imports System
Imports System.Threading.Tasks
Private ocr As New IronTesseract()
Using largePdf As New OcrPdfInput("PDFs/example.pdf")
Dim result = Await ocr.ReadAsync(largePdf)
DoOtherTasks()
Console.Write($"##### OCR RESULTS ###### " & $vbLf & " {result.Text}")
End Using
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'static void DoOtherTasks()
'{
' ' Simulate other tasks being performed while OCR is in progress
' Console.WriteLine("Performing other tasks...");
' System.Threading.Thread.Sleep(2000); ' Simulating work for 2000 milliseconds
'}為什麼要在IronOCR中使用異步和多線程?
IronOCR 結合了 async 支援和多執行緒,為現代應用程式開發提供了許多好處:
效能優勢:
- 提高吞吐量: 同時處理多個文件而不阻塞
- 更好地利用資源:最大化所有可用核心的CPU使用
- 降低延遲:立即開始處理而不必等待之前的操作完成
- 可擴展架構: 無需進行架構修改即可處理增加的工作負載
開發效益:
- 簡化程式碼: 不需要手動管理線程 - IronOCR處理複雜性
- 現代化模式: 完全支持Tesseract 5 for .NET中的異步/等待模式
- 輕鬆整合: 與現有的.NET異步基礎設施兼容
- 可維護的解決方案:清晰可讀的代碼,遵循.NET最佳實踐
IronOCR 中的多執行緒可大幅優化 OCR 任務。 內建的多線程功能結合ReadAsync()等方法可以簡化大批量文本數據處理。 此組合確保即使在處理大量資料時,應用程式仍然保持響應和高效,使IronOCR成為高性能軟體的有效工具,提供高效的文字識別能力。 要開始使用完整的功能集,請查看我們的NuGet套件安裝指南。
常見問題
IronOCR中的ReadAsync方法用於什麼?
IronOCR中的ReadAsync方法用於執行非同步的OCR操作,不會阻塞主執行緒,確保應用程式在文字識別任務期間保持回應。
IronOCR如何處理多執行緒?
IronOCR自動處理跨所有CPU核心的多執行緒,無需開發人員使用任何專門的API,優化系統資源並提升OCR性能。
OCR 處理中的多執行緒有哪些主要優點?
IronOCR的多執行緒實作提供自動的CPU核心利用、執行緒安全操作,透過MaxDegreeOfParallelism屬性可調整的記憶體佔用,以及隨著可用核心地增加而比例縮短的處理時間的可擴展性能。
為什麼非同步程式設計對IronOCR中的OCR很重要?
IronOCR中的非同步程式設計允許OCR任務在不阻塞主執行緒的情況下執行,保持應用程式的回應性並允許系統在執行OCR操作時處理其他任務。
我是否需要編寫特殊程式碼來啟用 OCR 的多執行緒?
不,多執行緒是預設啟用的,無需專門的API即可開始。程式庫將平行處理直接整合到OCR流程中,自動管理多個核心的執行緒以達到最佳性能。如果您需要限制該平行處理,請設置IronTesseract.MaxDegreeOfParallelism或使用MultiThreaded將其關閉。
OcrReadTask物件如何增強IronOCR的OCR操作?
IronOCR中的OcrReadTask物件提供增強的控制和靈活性,允許高效管理文字識別任務,特別有助於管理多個併發操作或使用中止標記取消任務。
在平行處理大量批次時如何限制記憶體使用?
設定IronTesseract.MaxDegreeOfParallelism以限制每次Read調用中同時OCR的頁面數量,或將MultiThreaded設置為false以串行閱讀。每個併發頁面使用其自己的原生Tesseract引擎,因此降低該值會直接降低峰值記憶體。請參閱限制平行OCR記憶體使用的指南以獲得默認值和優先級規則。
將MultiThreaded設置為false是否真的改變了什麼?
是。MultiThreaded在早期版本中沒有影響,但現在是一個即時設定。將其設置為false會使頁面在單一執行緒上順序讀取,提供最小且可預測的記憶體佔用,並覆蓋MaxDegreeOfParallelism。設置此屬性後預期其為惰性將在升級後順序讀取。
IronOCR 是否與 .NET 10 完全相容?
IronOCR 透過其最新發行版本 2025.12 支援 .NET 10。您可以使用 NuGet(Install-Package IronOcr)安裝該函式庫,並在 .NET 10 下執行類似 ReadAsync() 的動態方法,而無需特殊設定。