Using System.Threading.EventWaitHandle to block for an event

Posted in software by Christopher R. Wirz on Fri Sep 02 2016

Using System.Threading.EventWaitHandle to block for an event 2016-09-02

Ever since developers really started using Windows Presentation Foundation (WPF), the use of events for notification has grown in popularity too. This presents a challenge when developers must conform to an interface that provides a thread blocking return. Fortunately, the System.Threading provides an approach to Waiting for an event to complete. A developer can still hook onto an event, but now can return a value from the added execution body within a client method.

Note: Hooking onto an event multiple times will have adverse effects. It is prefered that the event object is scroped within the client method

As you may have guessed, this pattern is referred to as a semaphore. A semaphore is a variable used to control access to a common resource by multiple processes in a concurrent system.

The following code can be used to hook onto an event, but still provide a normal return.


// using System.Threading;

public IReturnedValue GetReturnValue(int timeout)
{
	// Create a return value scoped to the return
	IReturnedValue ret = null;
	
	// Create a semaphore
	EventWaitHandle semaphore = new AutoResetEvent(false);

	// Get a new object
	var objectWithReturnEvent = new ObjectWithReturnEvent();

	// Attach to the event
	objectWithEvent.ReturnEvent += (sender, args) =>
	{
		// Do things with the arguments, for example
		ret = (IReturnedValue)args.ReturnedValue;
		
		// set the semaphore
		semaphore.Set();
	};

	// The object will do something to arrive at the event
	objectWithReturnEvent.DoWorkToGetReturn();
	
	// Wait for the semaphore
	semaphore.WaitOne((int)timeout, true);
	
	// Return the value
	return ret;
}