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

2

10

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

Penicillium answered 2/1, 2011 at 12:57 Comment(0)
D
16

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

Duggan answered 2/1, 2011 at 13:38 Comment(0)
H
7

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.

Heterozygote answered 2/1, 2011 at 13:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.