我有两个OCR引擎。其中一个更快,但另一个有更好的认可(Abbyy)
所以我正在做的是启动两个在新的单独Thread上运行的OCRWorker。他们完成后举起一个事件。我在HandlerMethod中得到了两个引擎的结果,但我希望它们以某种方式同步并获得更好的结果。
此外,我想知道这种开始并列任务的方式是否是一种好方法,如果不会遇到可能的死锁。
这是我的代码:
本部分启动OcrEngineThreads
private void OnAreaSelected(object sender, EventArgs e)
{
var bmp = (Bitmap)SnippingTool.Image;
_runningOcrTasks = new List<Task>();
foreach (var engine in _ocrTextRecognizer)
{
var ocrWorker = new OcrWorker(bmp, engine);
ocrWorker.ocrFinishedEvent += OnOcrWorkerFinished;
ocrWorker.Run();
}
}
// Both Threads run into this Method
private void OnOcrWorkerFinished(object sender, OcrFinishedEventArgs args)
{
// I pass this point two times und would like
// to protect it from Deadlock and synchronize the result.
var result = args.Result;
}
class OcrWorker
{
private Thread t;
private Bitmap bmp;
private IOcrTextRecognition _ocrEngine;
public event OcrRecognitionFinishedEvent ocrFinishedEvent;
public OcrWorker(Bitmap bmp, IOcrTextRecognition ocrEngine)
{
this._ocrEngine = ocrEngine;
this.bmp = bmp;
this.t = new Thread(StartRecognizeText);
}
private void StartRecognizeText()
{
string result = this._ocrEngine.ScanImageForText(this.bmp);
OcrFinishedEventArgs finishedEventArgs = new OcrFinishedEventArgs(true, result);
if (ocrFinishedEvent != null)
{
ocrFinishedEvent.Invoke(this, finishedEventArgs);
}
t = null;
}
public void Run()
{
this.t.Start();
if (!t.Join(TimeSpan.FromSeconds(20))) {
#if (!DEBUG)
t.Abort();
throw new TimeoutException("OCR recognition took too long");
#endif
}
}
}
public delegate void OcrRecognitionFinishedEvent(object sender, OcrFinishedEventArgs args);
public class OcrFinishedEventArgs
{
public bool Success { get; }
public string Result { get; }
public OcrFinishedEventArgs(bool success, string result)
{
Success = success;
Result = result;
}
}