user1333935 user1333935 - 5 months ago 45
Vb.net Question

WCF Client Windows Service - How to handle connection errors?

I have a Windows Service running on a client machine which communicates to our server using WCF. The basic process is this:


  1. Every 3 minutes, the client makes a connection to the server using a DuplexChannelFactory (CreateChannel).

  2. While this connection is open, the server sends messages to the client.



The connection must remain open constantly because the server may need to communicate with the client at any time. This is why we are refreshing the connection every few minutes.

For the most part this system works fine. However if the client has a spotty Internet connection, the channel becomes aborted. Here's what happens in this case:


  1. The client opens a connection. This connection stays open for 3 minutes until it is closed and re-opened.

  2. During the first connection, the computer loses Internet connection for a few seconds.

  3. The Windows Service running on the client throws a System.Net.Sockets.SocketException and System.ServiceModel.CommunicationException. The code currently does not catch these exceptions.

  4. The computer regains Internet connection.

  5. The server tries to communicate with the client (still during the first 3 minutes).

  6. Since the first connection is still open, the server cannot communicate and gets the following error: The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it has been Aborted.



I'm trying to figure out how I can catch the errors that happen in step 3 so that I can close the current connection and re-open it. I currently have a function to handle the Faulted event, but this event is not hit when the connection is lost. I've tried looking into global error handling but it seems like most of the tutorials are for the server side, not client. Also, since the connection is just staying open indefinitely, there is nowhere I can put a try/catch block since there is no code that is actually running at the time it happens.

Answer

I was able to accomplish catching these exceptions by using the FirstChanceException event handler. I had to use this event because the exceptions were being handled automatically deeper down so I couldn't catch them.

In the Windows Service's OnStart function:

 Dim currentDomain As AppDomain = AppDomain.CurrentDomain
 AddHandler currentDomain.FirstChanceException, AddressOf HandleException

And the function I wrote checks if the exception is of a certain type I know the connection has failed and I create a new connection.

Comments