Reputation: 2939
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?
Upvotes: 1
Views: 268
Reputation: 315
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)
Upvotes: 1