Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.)

like image 367
Shaul Behr Avatar asked Jan 02 '11 12:01

Shaul Behr


2 Answers

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...

like image 116
marc_s Avatar answered Oct 22 '22 07:10

marc_s


Yes it is good practice to close the channel as soon as it is not needed any more. But it is not usual in case of Duplex communication. When you are using duplex communication you need opened channel to allow server send messages back to the client. WCF communication is always initiated by the client. Callback is allowed only by keeping channel initiated by the client openned.

Duplex communication involves some additional tasks to handle connection failures. Your service should contain some ping mechanism to allow client to check the connection in regular interval. If the connection fails client receives exception and you will be able to reestabilish connection. Also service should handle exception when sending callback message to faulted channel.

like image 23
Ladislav Mrnka Avatar answered Oct 22 '22 07:10

Ladislav Mrnka