1

我正在构建一个使用扫描仪 API 和图像到其他格式转换器的应用程序。我有一个方法(实际上是一个点击事件)可以做到这一点:

  private void ButtonScanAndParse_Click(object sender, EventArgs e)
  {
     short scan_result = scanner_api.Scan();

     if (scan_result == 1)
        parse_api.Parse(); // This will check for a saved image the scanner_api stores on disk, and then convert it.
  }

问题是 if 条件 (scan_result == 1) 是立即评估的,所以它不起作用。

如何强制 CLR 等到 API 返回方便的结果。

笔记

只需执行以下操作:

  private void ButtonScanAndParse_Click(object sender, EventArgs e)
  {
     short scan_result = scanner_api.Scan();
     MessageBox.Show("Result = " + scan_result);
     if (scan_result == 1)
        parse_api.Parse(); // This will check for a saved image the scanner_api stores on disk, and then convert it.
  }

它工作并显示结果。

有没有办法做到这一点,如何?

非常感谢你!

更新:

扫描仪 API 上有一个事件:

Public Event EndScan() // Occurs when the scanned the image.

但我不知道如何使用它。任何的想法?

4

3 回答 3

3

这实际上取决于 API 的工作方式。如果scanner_api.Scan() 被阻塞,那么它将坐在该行等待结果。一旦得到结果,if 将评估。这可能会导致您的 UI 变得无响应,因此您通常必须实现某种线程才能在后台执行此操作。我从你的问题中猜测这不是这个 API 的工作方式。

另一种可行的方法是使用polling。你经常检查一下,看看结果如何。您不想经常检查并用完所有资源(例如 CPU),因此您要定期检查。Sheldon 使用 Timer 的回答实现了这一点。

至少还有一种可行的方法是使用回调。您向 API 发送一个回调函数,以便在状态更新时调用。这可以实现为您绑定的事件(委托)或您作为参数传递的常规委托。您经常会看到这些实现为“OnStatusChanged”、“OnCompleted”等。

基本上,这取决于 API 支持什么。轮询通常有效,其他必须支持。如果可能,请查看您的 API 文档以获取示例。

于 2010-06-14T21:59:23.807 回答
1

一种方法是使用计时器。将计时器设置为每隔几秒检查一次,以检查 scan_result 中的值(需要将其提升为类级变量才能正常工作)。

所以,像:

public class Scanning
{
    private System.Timers.Timer aTimer;
    short scan_result;

    public Scanning()
    {
        aTimer = new System.Timers.Timer(1000);

        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
    }

    private void ButtonScanAndParse_Click(object sender, EventArgs e)
    {
       aTimer.Enabled = true;

       scan_result = scanner_api.Scan();
    }    

    private void OnTimedEvent(object source, ElapsedEventArgs e)
    {
       if (scan_result == 1)
       {
          aTimer.Enabled = false;

          parse_api.Parse(); // This will check for a saved image the scanner_api stores on disk, and then convert it.
       }
    }
}

(当然,这是未经测试的。YMMV。)

于 2010-06-14T21:22:39.657 回答
1

您可以使用计时器(请参阅MSDN:Timer 类)定期检查扫描是否已经完成。

您也可以使用在扫描过程完成时回调的异步调用。请注意,这是更复杂的方法。

于 2010-06-14T21:26:47.387 回答