Sometimes when I use assemblies that have an asynchronous approach for interaction (you call a method and then you get an event back with the answer) I like to convert them to synchrounus methods by embedding the event handler in the method.
The question is; I don't see this kind of code any where else so I'm getting a nasty feeling that there is some major drawback with this approach that I have missed and that everybody else is seeing. So what do you think - is it ok to write code like this?
Simple example of Logon method that embedds the event handler for the connection event.
private void Logon(GatewayConnection connection)
{
const int fiveSecondTimeout = 5000;
ManualResetEvent waitUntilOnlineEvent = new ManualResetEvent(false);
EventHandler<ConnectionEventArgs> connectionHandler = (sender, e) =>
{
if (connection.Status == ConnectionStatus.Connected)
waitUntilOnlineEvent.Set();
};
connection.ConnectionEvent += connectionHandler;
connection.Connect();
bool timeoutReached = !waitUntilOnlineEvent.WaitOne(fiveSecondTimeout);
connection.ConnectionEvent -= connectionHandler;
if (timeoutReached)
throw new ApplicationException("Logon failure");
}
I also think that this type of code, even if the actual method can become a little bit complex, can help in keeping a class that encapsulates a object with a lot of events clean and easy to read.