Passing an event as an argument to a method

I want to pass an event to a method. The code I have is as follows, but what did I set for the type "XXX"?

internal class Retriever<TEventArgs> where TEventArgs : EventArgs { public Retriever( XXX event, EventHandler<TEventArgs> handler ) { _event = event; _handler = handler; _event += handler; } XXX _event; EventHandler<TEventArgs> _handler; } 

Edit : Develop a question. I am trying to write an event generator where the event is signed before the event occurred and after the event occurred. This class will look like this:

 internal class EventGuard<TEventArgs> : IDisposable where TEventArgs : EventArgs { public Retriever( XXX event, EventHandler<TEventArgs> handler ) { _event = event; _handler = handler; _event += handler; } XXX _event; EventHandler<TEventArgs> _handler; public void Dispose() { _event -= _handler; } } 

and I will use it as follows. Proxy.RetrieveAsync is a web method that, when completed, will raise the Proxy.RetrieveCompleted event. The body of the HandleRetrieveCompleted completion HandleRetrieveCompleted , which is not shown, will call Set () in ManualResetEvent (passed as a UserState).

 using ( new EventGuard<EventArgs>( Proxy.RetrieveCompleted, new EventHandler<EventArgs>( HandleRetrieveCompleted) ) ) { ManualResetEvent resetEvent = new ManualResetEvent(); Proxy.RetrieveAsync(resetEvent); resetEvent.WaitOne(); } 
+4
source share
1 answer

You do not - the event is similar to a property, it is just syntactic sugar around a couple of methods (add / remove instead of get / set for the property). F # really reveals events as first-class citizens, but C # does not: (

There are several options:

  • Pass the delegate an β€œevent subscriber” that you invoke with the new handler you want to add (and possibly a delegate on behalf of the subscriber). Something like that:

     new Receiver(handler => button.Click += handler, ...) 
  • Go to EventInfo and subscribe with reflection (urgh)

  • Look at the Reactive Extensions framework, which has various ways of working with events (using reflection, but that means Microsoft is working on reflection, not with you :)

We could give better advice if we knew a more general picture - to take care to tell us more?

EDIT: Good, so in this case you will need to pass the subscription and unsubscribe code:

 using (new EventGuard<EventArgs>(h => Proxy.RetrieveCompleted += h, h => Proxy.RetrieveCompleted -= h, HandleRetrieveCompleted)) { ... } 

This is pretty unpleasant, admittedly. You may find something nicer there in Reactive Extensions , but it will at least work ...

+5
source

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


All Articles