Li Tian Gong
Li Tian Gong

Reputation: 393

WCF: keeping a client alive and time to close it

I have a wrapper around a WCF service APIs

Class APIWrapper
{
   private WCFClient _client;
   //constructor opens a client connection
   public APIWrapper()
   {
      _client = new WCFClient();
      _client.open();
   }

   public API1()
   {
       _client.doSomething1();
   }

   public API2()
   {
       _client.doSomething2();
   }

}

I want to ask:

Q1 will timeout exception occur? if this wrapper class instance exists for too long? (does the WCF connection by default keepalive? without setting that attribute in config) for example, after a wrapper class is constructed, its API1 or API2 is called after 10mins, which is longer than the timeout value of this WCF connection.

Q2 Do I need explicitly close the connection, if so, should I do it in the destructor of the wrapper class like below?

~APIWrapper
{
    if(_client !=null)
    try{
         _client.close();  }
    catch(Exception e){
         _client.Abort();   }
}

Upvotes: 0

Views: 2870

Answers (2)

fofik
fofik

Reputation: 1008

As I know, WCF do no keep the connection alive. After a predefined time passes (inactivityTimeout="00:10:00"), the connection will throw an exception when you try to call _client.doSomething1() or any other method on the service.

WCF inactivity timeout

To keep connection alive you should call a simple method at predefined intervals, lets say every 1 minute.

However, I agree with Jordi about that you should use wcf services stateless until it is realy necessary.

Upvotes: 2

Jordi
Jordi

Reputation: 2797

I am not sure why you wanna do that, but if the WCF is hosted in a IIS7, the WCF will start with or without connections, there is no point keeping a connection alive.

In my experience, those kind of services works best when are stateless (unless you have a really good reason). I strongly suggest opening and closing the connection each time. If you are doing this for performance, there are another ways to avoid closing and opening each time.

Q1: According to MSDN the openTimeout is 1 minute

http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.binding.opentimeout.aspx

Q2: you do not need to close the connection explicitly, but it's a good practice and I strongly recommend to do it. Non closing the connections could lead in a overhead on the WCF.

Upvotes: 4

Related Questions