tags:

views:

28

answers:

1

Hi All,

I have a wcf client.

What is the best way of handling connections ?

Is it to open and close every time you need to contact the service:

void doSomething(){  
    MyService service = new MyService();  
   //try   
   service.doThis(10);  
   ...  
   service.doThat(20);  
   service.Close()  
   // catch   
}  

Or should I keep opened reference and abort it and reinitialize if connection error occurs:

class Myclass{  
   MyService service = new MyService();  
   ...   
   void myFunction(){  
     try{  
         service.doThis(10);  
     }catch(...){  
         service.abort();  
         service = new Myservice();  
         // do something here, but what it a smart thing to to?  
     }  
   }  
}

Regards

+1  A: 

First approach is common. Second approach is completely wrong. The most important hint to your question is: If you close/abort the proxy, you can't use it again. It opens only once.

If you use first approach you create new proxy each time and you "open" new connection. The open here can have different meaning for different bindings and situations. After making the call you gracefully close the proxy. This will also inform the server about closing connection.

Second approach uses similar steps except the last one which forcibly closes the connection. This will not inform the server about connection closing. But you will not be able to reuse unclosed connection on the server.

If you want to reuse proxy you have to left it opened. Than you have to handle some other complexity with timeouts on server (receiveTimeout - by default connection is closed after 10 minute of inactivity) and unhandled exceptions. If you have session based connection or service each unhandled exception will make the communication channel faulted and you will be only able to call Abort on the channel.

Ladislav Mrnka
If the first approach is common, does it make overhead opening new connection every time or the overhead is negligible ?
darko petreski
It depends on type of application you are building and on frequency of calls.
Ladislav Mrnka
One call per 5-6 sec, 200 clients in paralel
darko petreski
And the service client is application running on client machine or web application?
Ladislav Mrnka
The client is desktop application, and the service is hosted in iis 6
darko petreski
So I suppose you are using BasicHttpBinding. Than you can maintain single proxy in your desktop application. BasicHttpBinding does not use any type of session so no additional complexity should be involved.
Ladislav Mrnka