3

In Dustin Campbell's answer in question Return a value from a Event — is there a Good Practice for this? it is stated that instead of returning data from an event handler, we can have a writable property on a set of custom EventArgs that is passed to the event similar to Cancel property of the WinForms FormClosing event.

How do I provide feedback to event caller using properties in EventArgs?

My specific scenario is that there is a Controller class that does Job A and there are many classes requesting the Job A to be done. Thus, the controller is subscribed to this event on all classes.

I want to give some feedback to the caller that the job is done. The tricky part is that those classes are module-like and controller doesn't know anything about them.

My though is to include that writable property to the delegate of the event in order for the controller to give feedback through it. This property could somehow be invoked using reflection, which is fine in my scenario.

4

1 回答 1

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);
  }
}
于 2012-11-22T02:13:14.043 回答