0

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?

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438

2 Answers2

1

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();
}
Pavel
  • 524
  • 4
  • 8
  • Actually, this is one of the very few places to _not_ use a `using` block. See http://stackoverflow.com/questions/573872/what-is-the-best-workaround-for-the-wcf-client-using-block-issue?rq=1. – John Saunders Nov 07 '13 at 09:07
1

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.

Wim Ombelets
  • 5,097
  • 3
  • 39
  • 55
  • 1
    Actually, this is one of the very few places to _not_ use a `using` block. See http://stackoverflow.com/questions/573872/what-is-the-best-workaround-for-the-wcf-client-using-block-issue?rq=1. – John Saunders Nov 07 '13 at 09:07
  • very interesting to know, thanks John. I stand corrected and will edit my answer – Wim Ombelets Nov 07 '13 at 09:09
  • Hmm... Who put +1 on the reply below advocating usage of *using* and defending the application of *Close()*? Based on the information, I'd like to see **this** reply as more +ified but I've by principle avoided downvoting. – Konrad Viltersten Nov 07 '13 at 09:58