Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I've rushed together a working sample in LinqPad using reflection, getting a reference to the EventInfo object with a string (be careful as you loose compile time checking). The obvious issue is that there is no guarentee an event will ever be fired, or that the event your expecting may be fired before the EventWaiter class is ready to start blocking so I'm not sure I'd sleep comfy if I put this in a production app.</p> <pre><code>void Main() { Console.WriteLine( "main thread started" ); var workerClass = new WorkerClassWithEvent(); workerClass.PerformWork(); var waiter = new EventWaiter( workerClass, "WorkCompletedEvent" ); waiter.WaitForEvent( TimeSpan.FromSeconds( 10 ) ); Console.WriteLine( "main thread continues after waiting" ); } public class WorkerClassWithEvent { public void PerformWork() { var worker = new BackgroundWorker(); worker.DoWork += ( s, e ) =&gt; { Console.WriteLine( "threaded work started" ); Thread.Sleep( 1000 ); // &lt;= the work Console.WriteLine( "threaded work complete" ); }; worker.RunWorkerCompleted += ( s, e ) =&gt; { FireWorkCompletedEvent(); Console.WriteLine( "work complete event fired" ); }; worker.RunWorkerAsync(); } public event Action WorkCompletedEvent; private void FireWorkCompletedEvent() { if ( WorkCompletedEvent != null ) WorkCompletedEvent(); } } public class EventWaiter { private AutoResetEvent _autoResetEvent = new AutoResetEvent( false ); private EventInfo _event = null; private object _eventContainer = null; public EventWaiter( object eventContainer, string eventName ) { _eventContainer = eventContainer; _event = eventContainer.GetType().GetEvent( eventName ); } public void WaitForEvent( TimeSpan timeout ) { _event.AddEventHandler( _eventContainer, (Action)delegate { _autoResetEvent.Set(); } ); _autoResetEvent.WaitOne( timeout ); } } </code></pre> <p>Output</p> <pre><code>// main thread started // threaded work started // threaded work complete // work complete event fired // main thread continues after waiting </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload