1

If I have a loop in which I create CommunicationObject (ClientBase to be exact), is there a need to call Close() function after its using?

while(true)
{
 Service client = new Service();
 client.Close() // is in necessary? 
}

does CommunicationObject use any system resources that still remain after CLR collecting? and if so, what will happen if I don't close it? is there a probability to drop the service?

Wachburn
  • 2,842
  • 5
  • 36
  • 59
  • Yes you need to. Otherwise the connection will not be closed. Also there are some problems will appear when disposing the service client [refer this question for details](http://stackoverflow.com/questions/573872/what-is-the-best-workaround-for-the-wcf-client-using-block-issue) – Sriram Sakthivel May 19 '15 at 07:24

1 Answers1

1

Yes you need to close it. In fact Service is disposable, so use the using statement as such:

using(var client = new Service()){
   ...
} // <-- this line will trigger the Close();

There is a little problem though. The Close method might throw an exception in case the client state is faulted. The correct thing to do would be something like this:

try
{
    ...
    client.Close();
}
catch (CommunicationException e)
{
    ...
    client.Abort();
}
catch (TimeoutException e)
{
    ...
    client.Abort();
}
catch (Exception e)
{
    ...
    client.Abort();
    throw;
}

As suggested here: https://msdn.microsoft.com/en-us/library/aa355056%28v=vs.110%29.aspx

Personally i find this a bit of an overkill.. I always just use the using statement. (first code sample)

Clark Kent
  • 305
  • 1
  • 4
  • 16