tags:

views:

100

answers:

2

In my client program, there is a WCF connection that is opened at startup and supposedly stays connected til shutdown. However, there is a chance that the server closes due to unforeseeable circumstances (imagine someone pulling the cable).

Since the client uses a lot of contract methods in a lot of places, I don't want to add a try/catch on every method call.

I've got 2 ideas for handling this issue:

  1. Create a method that takes a delegate and executes the delegate inside a try/catch and returns an Exception in case of a known exception, or null else. The caller has to deal with nun-null results.

  2. Listen to the Faulted event of the underlying CommunicationObject. But I don't see how I could handle the event except for displaying some error message and shutting down.

Are there some best practices for faulted WCF connection that exist for app lifetime?

+1  A: 

If you do have both ends of the wire under your control - both the server and the client are .NET apps - you could think about this approach instead:

  • put all your service and data contracts into a shared assembly, that both the server and the client will use

  • create the ChannelFactory<IYourService> at startup time and cache it; since it needs to have access to the service contract, this only works if you can share the actual service contract between server and client. This operation is the expensive part of building the WCF client

    ChannelFactory<IYourService> factory = new ChannelFactory<IYourService>();
    
  • create the actual communications channel between client and server each time you make a call, based on the ChannelFactory. This is pretty cheap and doesn't cost much time - and you can totally skip any thoughts about having to detect or deal with faulted channels.....

    IYourService client = factory.CreateChannel();
    client.CallYourServiceMethod();
    

Otherwise, what you basically need to do is wrap all service calls into a method, which will first check for a channel's faulted state, and if the client proxy is faulted, aborts the current one and re-creates a new one.

marc_s
I'm already doing the first 2 bullet points you suggested, I should have added that info to the question. However, I dislike your third point: Creating a channel requires a certain amount of try/catch as well, so I did not gain anything.
mafutrct
As for the last paragraph, I guess I like that idea. I did not think of attempting to recreate the channel, nice idea.
mafutrct
+1  A: 

I wrote a blog post on exceptions in WCF that deals with how to handle this: http://jamescbender.com/bendersblog/Default.aspx

James Bender