Is it imperative to explicitly close the client?

66 Views Asked by At

I've seen a pre-existing code that uses automatically generated client for accessing a WCF. The original version, as suggested on the auto-generated page is as follows.

public int GetNumber()
{
  ServiceClient client = new ServiceClient();
  int number = client.GetNumber();
  client.Close();
  return number;
}

It's been refactored to the following.

public int GetNumber()
{
  ServiceClient client = new ServiceClient();
  return number.GetNumber();
}

I'm not sure if it's guaranteed that the client will be closed (be that by GC or any other thingy). Is it or should I suggest adding the two lines of code?

2

There are 2 best solutions below

3
On BEST ANSWER

From what I understand, you are correct in that the .Close() can be omitted.
As long as there are incomplete asynchronous tasks, the client will not be disposed, not by calling .Close() and not by the client object going out of scope. A using statement for WCF services appears to be ill-advised, as the (great) link from John in the comments below indicates.

1
On

You need to invoke Close method. Or use following code snippet which despose client object on exit out of using block

using(ServiceClient client = new ServiceClient())
{
    return number.GetNumber();
}