WCF - is it bad practice to leave a channel open for a long time?

Shaul Behr picture Shaul Behr · Jan 2, 2011 · Viewed 7.3k times · Source

I'm just learning the ropes around WCF. What I was planning to do was have a duplex channel open between a client and server using NetTcpBinding, and keep that open indefinitely so that the server can initiate requests to the client.

Then I stumbled upon this blog by Jesse Ezell, which seems to indicate that it's a Bad Thing to keep a channel open indefinitely, because you can't catch faults, and that causes all manner of instabilities.

Is that correct? If I use NetTcpBinding and keep a reference to an open channel on either side of the relationship, what happens if there's a communication failure? How do I catch the failure event? What other gotchas are there? Is there any difference which .NET framework you're using? (I'm on 4.0.)

Answer

marc_s picture marc_s · Jan 2, 2011

I don't agree with Jesse (as a side note: he also recommends you use WCF service classes as singletons by default, which is the worst idea ever in my opinion).....

As long as you take good care of catching exceptions on the server (e.g. by implementing the IErrorHandler interface in your service class), there's no point here to keep shutting down your channel... especially not in a corporate LAN environment using netTcpBinding.

Contrary to e.g. a database connection which often incurs licensing costs, keeping a network connection to your service machine open shouldn't cause any issues. It's also usually not a limited resource, so constantly opening and closing it seems pointless.

If you do keep your service channel open for a longer period of time, you need to be capable on the client side to handle faults - e.g. you need to be able to recover from a situation where the channel has become faulted, when an exception has occured after all (e.g. the network is down or something like that).

But if you do that, then I don't see any benefit in constantly closing your channel after every call, and reopening for the next...