WCF channel lifetime with repeat calls
Maybe this is an obvious question, maybe it isn't. Imagine a GUI control application where every button push calls a different function on a remote WCF service. Button usage is frequent at approximately every few seconds. In gen开发者_C百科eral is it best to open and close the WCF channel every function call or hold the channel open for the lifetime of the application? Assuming of course that there is only ever a few instantiations of this application.
NB. This question is not really about the example, but in helping me get my head around the best practice here.
If you can spare yourself from having to recreate the client proxy before every call, that would definitely be beneficial for your performance.
BUT: doing so, you must ensure that all exceptions on the server-side are handled properly (maybe by implementing the IErrorHandler
interface on your service) and turned into SOAP faults, which can be transferred back to the client without faulting the channel.
If a single exception escapes you, and get sent back to the client as a "regular" .NET exception, the channel (the communication link between your client and your server) will be faulted --> i.e. rendered useless.
In such a case, you need to first check for that state (the channel has a .State
property), and if you encounter a faulted channel, there's nothing you can do except re-create the client proxy again before calling methods on it.
It is not recommended to leave the channel open but leave WCF to decide when to physically close\open channels. You can save some resources by using the same client object over and over again just make sure no 2 threads use it at the same time (in case 2 buttons can be pressed at once or one right after the other).
精彩评论