Thursday, January 20, 2011

Do Not use using statement to close WCF connections

Here are good articles:

http://msdn.microsoft.com/en-us/library/aa355056.aspx
http://codeguru.earthweb.com/csharp/.net/net_general/tipstricks/article.php/c15941/

When call WCF client, this block of code has problem:

using (MyWcfClient myclient = new MyWcfClient())
{
myclient.MyFunction();
}

the reason is after finish the using block, ClientBase.Close() method is forcedly called. There may comes out network connection exception.

The proper code can be:

MyWcfClient myclient = new MyWcfClient();
myclient.MyFunction();
try
{
if (myclient.State != System.ServiceModel.CommunicationState.Faulted)
{
myclient.Close();
}
}
catch (Exception ex)
{
myclient.Abort();
}

or we can simplify the code to be:
MyWcfClient myclient = new MyWcfClient();
try
{ myclient.MyFunction();
myclient.Close();
}
catch
{
myclient.Abort();
}

In this case we can close wcf connection properly.

Note: someone argued this is one of Microsoft bug, but when we close wcf client, we should take notice of this.

New notes in 2011:

As the above code doesn't follow FxCop, the service client is not always been disposed, we can write this code as:

MyWcfClient myclient = new MyWcfClient();
try
{ myclient.MyFunction();
}
catch
{
myclient.Abort();
}
finally
{
myclient.Close();
}

No comments: