2

I have WCF service, called by ASP.NET web application. When there is more than one call per page request, is it better to keep client open and share the instance across the whole request, or is it better to create and dispose client per each service call as shown below?

using (var client = new WcfClient())
{
    var result = client.Method();
}
Fanda
  • 3,760
  • 5
  • 37
  • 56
  • Its better to write code to that does everything in one hit. If you have a handful of exceptions, I would create and destroy the client and not keep it around. – granadaCoder Apr 24 '14 at 11:58

1 Answers1

3

If you're using webHttpbinding, wshttpbinding or basicHttpbinding, the default behavior is for each client request (call) to get its own unique connection and instance of the web service object(s). This means that when Client A and B send requests to your web service, each will get it's own instance of the service, instantiated by the hosting program, then disposed of neatly (hopefully) when the response is sent back to the client. The WCF .NET infrastructure and the hosting program take care of all of the creation and destruction of the connections and objects for you, unless you hijack the process and do something fancy.

It's possible to create persistant client sessions that leave a connection open and the service in memory, but I've never tried it. Here's a link to an explanation of how to do it: WCF sessions with a wsHttpBinding and without windows security

For the last two years, I've worked entirely on WCF client and host software on an industrial scale and there's not much reason to worry about the efficiency of continuously openning and closing connections on a WCF web service. I've benchmarked our tests services with hundreds of concurrent client connections, each uploading and downloading files, and it barely stresses the WCF server's CPU. During our tests, the majority of the stress (as usual) fell on the database side.

Community
  • 1
  • 1
Brian
  • 3,653
  • 1
  • 22
  • 33