views:

48

answers:

1

Hello,

I'm working on a Silverlight application that works with WCF services. While loading the service metadata in my browser, I noticed that it provides the following code:

class Test
{
    static void Main()
    {
        myServiceClient client = new myServiceClient();

        // Use the 'client' variable to call operations on the service.

        // Always close the client.
        client.Close();
    }
}

The last line says "Always close the client". My question is, when should you close the client in a Silverlight application? Should you close it after your call to "[MyServiceOperation]Async" or should you close it in the "[MyServiceOperation]Completed" event handler?

Thank you,

+2  A: 

Close blocks when used in an asynchronous scenario.

There is also a BeginClose/EndClose asynchronous variant of the code if you do not want your calling code to block, but from what I can see if you call .Close it will wait until your outstanding calls resolve before .Close returns.

Also note that calling it in your Completed handler may cause issues with multiple async calls to the same client object... I would recommend doing it in the calling code either with .Close or .BeginClose

Updated: From the documentation (although somewhat buried)

This method causes an ICommunicationObject to gracefully transition from the Opened state to the Closed state. The Close method allows any unfinished work to be completed before returning. (For example, finish sending any buffered messages.)

...

Close returns after the Closed state is reached.

Ben Von Handorf