Passing an event handler as a parameter

Well, I really don’t know what is wrong with my code, and what happens like this.

class Activity has the following methods

 protected struct EventParams { public object sender; public EventArgs e; } private EventParams WaitEventRaise_Body(ref EventHandler<EventArgs> handler, int timeout) { AutoResetEvent receiver = new AutoResetEvent(false); EventParams result = new EventParams(); EventHandler<EventArgs> handle = new EventHandler<EventArgs>((sender, e) => { result.e = e; result.sender = sender; receiver.Set(); }); handler += handle; if (timeout > 0) { receiver.WaitOne(timeout); } else { receiver.WaitOne(); } return result; } protected EventParams WaitEventRaise(ref EventHandler<EventArgs> handler) { return WaitEventRaise_Body(ref handler, -1); } protected EventParams WaitEventRaise(ref EventHandler<EventArgs> handler, int timeout) { return WaitEventRaise_Body(ref handler, timeout); } 

So, I find myself writing AutoResetEvent again and again, so I decided to create a method. But when I try to call this method from the derived class Bot : Activity

 EventParams eventResult = WaitEventRaise(ref currentJob.JobReported); 

gives

Error 30 The best overloaded method matching for Project.Activity.WaitEventRaise (ex System.EventHandler) has some invalid arguments

currentJob is a Job : Activity class that has an event

 public event EventHandler<JobReport> JobReported; 

and

 class JobReport : EventArgs 

What I want to do is that the bot does the job, actually creates jobs and waits for them to finish their work. The Job class fires an event inside so that the bot class notices that it has completed its work. And the bot class waits until work triggers an event. Therefore, I hope this is clear. And I'm sorry that English is not my native language.

+4
source share
2 answers

Basically, you cannot refer to such an event. Two options:

  • Pass delegates “add handler” and “remove handler”:

     EventParams eventResult = WaitEventRaise<JobReport>(handler => currentJob.JobReported += handler, handler => currentJob.JobReported -= handler); 

    where WaitEventRaise will be declared as:

     EventParams WaitEventRaise<T>(Action<EventHandler<T>> add, Action<EventHandler<T>> remove) where T : EventArgs 
  • Go to EventInfo corresponding to the event you selected with reflection

None of them are terribly nice - this is the problem that Rx faces.

+6
source

I don’t know what the Job class contains or what currentJob.JobReported , but judging by the WaitEventRaise error WaitEventRaise , it requires System.EventHandler , which is a method like

 private void MeMethod(object sender, EventArgs e) { } 
0
source

Source: https://habr.com/ru/post/1494285/


All Articles