使用EventArgs中的可写属性向事件调用者提供反馈

时间:2012-10-08 09:18:34

标签: c# .net events reflection

在Dustin Campbell的回答问题Return a value from a Event — is there a Good Practice for this?中,声明不是从事件处理程序返回数据,而是在一组传递给事件的自定义EventArgs上有一个可写属性类似于WinForms FormClosing事件的Cancel属性。

如何使用EventArgs中的属性向事件调用者提供反馈?

我的具体情况是有一个执行Job A的Controller类,并且有许多类要求完成Job A。因此,控制器在所有类上订阅此事件。

我想向调用者提供一些反馈,告知他们已完成工作。棘手的部分是这些类是模块式的,控制器对它们一无所知。

我的意思是将writable property包含在事件的委托中,以便控制器通过它提供反馈。可以使用反射以某种方式调用此属性,这在我的场景中很好。

1 个答案:

答案 0 :(得分:1)

您无法定义委托的属性。 此外,您不需要反射这种机制。 你想要做的是在EventArgs派生类中定义你的“返回”属性。

一个简单的类是:

public class JobEventArgs : EventArgs {
  public bool Done { get; set; }
}

现在您可以在课程中将您的活动声明为

public event EventHandler<JobEventArgs> Job;

处理事件的方法中的用法:

public void DoJob(object s, JobEventArgs args) {
  // do stuff
  args.Done = true;
}

并且在调用代码的事件中:

public void FireJobEvent() {
  var args = new JobEventArgs();

  this.Job(this, args);

  if(!args.Done) {
    // the job was not handled
  }
}

但坦率地说,你似乎希望在通知结束后与通知异步完成工作。

这会产生类似..

的语法
class Module {
  public void JobCompleted(IAsyncResult r) {
    if(!r.IsCompleted)
      return;

    Console.WriteLine("The job has finished.");
  }

  public void ExecuteJob() {
    var job = new EventArgs<JobEventArgs>((s, a) => { this.controller.JobA(); });
    job.BeginInvoke(null, null, 
      r => 
      { 
        this.JobCompleted(r); 
        if(r.IsCompleted) 
          job.EndInvoke(r); 
      }, null);
  }
}