【问题标题】:How Can I Avoid Invoking Every Event From My External Library?如何避免从我的外部库中调用每个事件?
【发布时间】:2009-10-13 09:24:07
【问题描述】:

我编写了一个库,它使用我们的定制嵌入式硬件处理所有 TCP/IP 通信。它与我们的大多数内部软件一起使用,将来可能会单独出售。

最烦人的是,每次我处理来自库的事件时,我都必须有一个单独的函数来调用。我只能想象有一种更简单的方法可以做到这一点,我只是不知道......

有什么想法吗?

    public Setup(DiscoveryReader reader)
    {
        download = new DownloadFilesIndividual(Reader.ip, DateTime.Today);
        download.OnDownloadStatus += new DownloadStatusHandler(download_OnDownloadStatus);
    }

    void download_OnDownloadStatus(DownloadStatus status)
    {
        Invoke(new DownloadStatusHandler(this.safe_download_OnDownloadStatus), new object[] { status });
    }

    void safe_download_OnDownloadStatus(DownloadStatus status)
    {
        // Do UI stuff here
    }

【问题讨论】:

  • 这样做的确切原因是什么? safe_download 实际上如何“更安全”?
  • 啊,我明白了。 “用户界面的东西”,呵呵。
  • 调用是必需的,因为该库正在另一个线程中运行 tcp 内容。 tcp 线程然后触发不能直接操作表单的事件。 safe_download 实际上并不安全,只是我养成了在开头添加一个词的习惯

标签: c# multithreading invoke


【解决方案1】:

语法糖

public Setup(DiscoveryReader reader)
{
    download = new DownloadFilesIndividual(Reader.ip, DateTime.Today);
    download.OnDownloadStatus += new DownloadStatusHandler(download_OnDownloadStatus);
}

void download_OnDownloadStatus(DownloadStatus status)
{
   if(InvokeRequired)
   {
    Invoke(new Action<DownloadStatus>(download_OnDownloadStatus),status);
   } else {
   // Do UI stuff here
   }
}

【讨论】:

  • 我喜欢这个!我不知道 Action。如果我能以某种方式将调用包含在库中,那就太好了,但我不确定这是否可能!
  • 为什么是“Invoke(new Action(download_OnDownloadStatus, status));”给我“错误 - 需要方法名称”
  • 解决了,应该是:Invoke(new Action(download_OnDownloadStatus), status);
猜你喜欢
  • 2018-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-11
  • 1970-01-01
  • 1970-01-01
  • 2012-11-19
相关资源
最近更新 更多