2

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.

Patrik B
  • 151
  • 1
  • 13
  • I see nothing wrong with this approach. Its just some kind of synchronizing an asynchronous method. You could refactor your method so that you can use it with any asnyc method. – Jan Nov 21 '12 at 14:23
  • 1
    In his book "CLR via C# 3rd Edition" Jeffrey Richter shows an example on how to convert the Event Asynchronous Pattern to a Task. He also shows how to convert the Async Programming Model to a Task. By the way have a look at this article on MSDN comparing ManualResetEvent and ManualResetEventSlim (http://msdn.microsoft.com/en-us/library/5hbefs30.aspx). If the event is very short then ManualResetEventSlim can perform better. In your specific example it will probably not, though. – Panos Rontogiannis Nov 21 '12 at 15:11

0 Answers0