Search code examples
c#wcfwcfserviceclient

Is it imperative to explicitly close the client?


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?


Solution

  • 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.