使用TWAIN异步扫描文档

时间:2017-07-06 21:10:31

标签: c# .net asynchronous backgroundworker twain

我有一个C#程序,它使用TwainDotNet扫描和接收来自fujitsu扫描仪的图像。我有工作代码,但我想异步执行扫描和图像传输,因为GUI会挂起,直到扫描过程完成。

我尝试使用此代码遵循this post's已接受解决方案中的指南:

public void StartScanning()
{
    // Run the scanner from a separate thread
    Task.Run(() => ScanThread());
}

private void ScanThread()
{
    // Instantiate the Twain object and hookup event handlers
    Twain twain = new Twain(new WinFormsWindowMessageHook(new Form()));
    twain.TransferImage += Twain_TransferImage;
    twain.ScanningComplete += Twain_ScanningComplete;

    // Start the scanning process by passing along pre-defined scan settings
    twain.StartScanning(GetScanSettings());
}

ScanThread()内的代码在技术上是正确的,因为它在调用Task.Run()之外工作(意味着它在GUI线程上运行正常)。但是,如果从新线程调用ScanThread(),则{{1}}不起作用。扫描仪硬件永远不会开始扫描图像,更不用说传输它们了。

有没有人知道使用TWAIN异步扫描和传输图像的具体方法?

1 个答案:

答案 0 :(得分:0)

我怀疑"简单"答案是"你不能"。

更复杂的答案是" twain" (或者可能" GetScanSettings" - 这是做什么用的?)可能需要在UI线程上执行操作。

请参阅:TwainDotNet Scanning using TWAIN with BackgroundWorker

但是,使用您已获得的代码可能是可能的,除非您创建的表单在引用较弱时几乎立即超出范围(例如事件委托)。

尝试添加线程安全列表或字典,在创建时将表单添加到其中,然后在Twain_ScanningComplete中删除它。

嗯。 实际上,试试

private ConcurrentDictionary<Twain,Form> m_References = new ConcurrentDictionary<Twain,Form>();


private void ScanThread()
{
    // Instantiate the Twain object and hookup event handlers
    Form frm = new Form();
    Twain twain = new Twain(new WinFormsWindowMessageHook(frm));
    m_References.Add(twain, frm);

    twain.TransferImage += Twain_TransferImage;
    twain.ScanningComplete += Twain_ScanningComplete;

    // Start the scanning process by passing along pre-defined scan settings
    twain.StartScanning(GetScanSettings());
}


private void Twain_ScanningComplete(object sender, ScanningCompleteEventArgs args)
{
    Form frm;
    m_References.TryRemove((Twain) sender, out frm);
    if(null != frm)
    {
       frm.Close();
    }
}