在UI线程中引发事件

时间:2012-05-25 09:33:31

标签: c# winforms compact-framework

我需要在UI线程中引发事件,我发现的所有解决方案仅适用于完整框架:例如,使用GetInvocationList和ISynchronizeInvoke的非常简单的解决方案,但NET CF不支持ISynchronizeInvoke。有没有办法在CF的UI线程中引发事件?我的代码如下。我使用.NET CF 3.5

class Publisher {
  public event EventHandler OnEventHandler;
  private void OnEvent()
  {
    var handler = OnEventHandler;
    if (handler != null) handler(this, EventArgs.Empty); 
  }
}

1 个答案:

答案 0 :(得分:0)

我使用必须声明的MethodInvoker(因为它在紧凑框架下不存在),然后包含指向父控件的链接(通常是主窗体):

class Publisher {
  #if PocketPC // MethodInvoker delegate is not declared in CF!
  public delegate void MethodInvoker(); 
  #endif
  private Form _parent;

  public Publisher(Form parent) {
    _parent = parent;
  }

  public event EventHandler OnEventHandler;
  private void OnEvent() {
    if (OnEventHandler != null) {
      MethodInvoker mi = delegate { OnEventHandler(this, EventArgs.Empty); };
      try {
        _parent.BeginInvoke(methInvoker);
      } catch (ObjectDisposedException) {
      } catch (NullReferenceException err) {
        LogError("OnEvent NullReference", err);
      } catch (InvalidOperationException err) {
        LogError("OnEvent InvalidOperation", err);
      }
    }
  }
}

希望你能够做到这一点。 ;)

〜乔