.net - How to pass around event as parameter in C# -


I am writing unit tests for multi-threading applications, as far as I have to wait until a specific event is triggered. So that I know the asynchronous operation is done. For example, when I call repository.add (some) , I wait for an event before I make any arguments. So I wrote a utility function to do this:

  Public static zero sync (EventHandar Event_, Action Action_) {var Signal = New Object (); Event handler callback = faucet; Callback = new event hereler ((s, e) => gt; lock (signal) {monitor. Pulse (signal);} event_ - = callback;}); Event_ + = Callback; Lock (hint) {action_ (); Assign Truth (wait for monitor (signal, 10000)); }}  

However, the compiler stops the class from passing the event. Is there any way to get that?

Solution using reflection below. Public static void SyncAction (object target_, string event_, action action_) {SyncAction (new list & lt; pair & lt; object, string & gt; & gt; () {new Pair & lt; Object, String & gt; (target_, event_)}, Action_); } Public static void SyncAction (IEnumerable & LT; pair & lt; object, string & gt; & gt; events_, action action_) {var events = events_ .Select (a => New pair of & lt; Object, EventInfo & gt; (a.First, a.First.GetType () .GetEvent (a.Second)). Where (a => a.Second! = Null); Var count = events.Count (); Var signal = new object (); Var callback = new event handler ((s, e) => gt; lock (signal) {-t; monitor; pulse (signal);}}); Events.ForEach (a => a.Second.AddEventHandler (a.First, Callback)); Lock (hint) {action_ (); While (calculation> 0) {Assert.IsTrue (Monitor.Wait (sign, 10000)); }} Events.ForEach (a => a.Second.RemoveEventHandler (a.First, Callback)); }

The problem is that the incidents are not actually the first class values.

  • You can provide the name and the name of the event, and this will use the reflection ... something like this:

      on x = Observable.FromEvent & LT; EventArgs & gt; (Button, "click on");  
  • You can provide a representative for membership and a representative to finish the subscription:

      on x = Observable.FromEvent & LT; EventArgs & gt; (Handler = & gt; button.Click + = Handler, Handler = & gt; Button = Click = = Handler);  

(Exact ways can be a bit different, but this is a common idea.)

Of course, If you are happy to use, you can use those methods and make your test use IObservable & lt; T & gt; :)


Comments