在C#中實現TWIN的多線程掃描,你需要遵循以下步驟:
using System;
using System.Threading;
using System.Collections.Concurrent;
using System.Security.Cryptography;
public class ScanResult
{
public string ImagePath { get; set; }
public string Text { get; set; }
}
public class TwainDeviceManager
{
private const int MAX_DEVICES = 10;
private TwainDevice[] _devices;
private Semaphore _semaphore;
public TwainDeviceManager()
{
_devices = new TwainDevice[MAX_DEVICES];
_semaphore = new Semaphore(MAX_DEVICES, true);
}
public void AddDevice(TwainDevice device)
{
_semaphore.WaitOne();
for (int i = 0; i < MAX_DEVICES; i++)
{
if (_devices[i] == null)
{
_devices[i] = device;
break;
}
}
_semaphore.Release();
}
public void RemoveDevice(TwainDevice device)
{
_semaphore.WaitOne();
for (int i = 0; i < MAX_DEVICES; i++)
{
if (_devices[i] == device)
{
_devices[i] = null;
break;
}
}
_semaphore.Release();
}
public void StartScanning()
{
Thread[] threads = new Thread[MAX_DEVICES];
for (int i = 0; i < MAX_DEVICES; i++)
{
if (_devices[i] != null)
{
threads[i] = new Thread(() =>
{
_devices[i].StartScanning();
});
threads[i].Start();
}
}
}
public void StopScanning()
{
for (int i = 0; i < MAX_DEVICES; i++)
{
if (_devices[i] != null)
{
_devices[i].StopScanning();
}
}
}
public ScanResult GetNextScanResult()
{
for (int i = 0; i < MAX_DEVICES; i++)
{
if (_devices[i] != null && _devices[i].HasScanResult)
{
ScanResult result = _devices[i].GetScanResult();
_devices[i].ResetScanResult();
return result;
}
}
return null;
}
}
public class TwainDevice
{
private string _name;
private bool _isScanning;
private ScanResult _scanResult;
public TwainDevice(string name)
{
_name = name;
_isScanning = false;
}
public string Name
{
get { return _name;