If you call a WCF service, you need to be aware of a problem if you invoke it in the using statement like the following code.
using (cnblogswcfclient client = new Cnblogswcfclient ())
{
Client. Dour ("Hello, cnblogs.com!");
}
The above code looks fine, Cnblogswcfclient is an automatically generated WCF client Agent that inherits from System.ServiceModel.ClientBase. At the end of a using statement, the System.IDisposable.Dispose interface of the ClientBase implementation is invoked, which in fact calls the close () method of the ClientBase. Open C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.ServiceModel.dll with. NET Refector, you can see this code, see the following figure:
Not only does it look okay, it seems to be fine. But... The problem is that on clientbase.close (), close () closes a network connection, and if there is a problem with the network connection, an exception is thrown (the ClientBase Close method is designed to throw an exception instead of forcing the shutdown). That's the problem. We used the purpose is that no matter what the situation, even if the sky fell down, but also to shut me off; As a result, shut is closed, but not closed, the sky still collapsed.
Maybe we can dodge this problem with irresistible force, but the programmer's instinct is to solve the problem. Any small problem in the code cannot be overlooked because it is difficult to anticipate that this small problem will not cause major problems.
How to solve the problem? There are answers in MSDN (go to MSDN for a look) and the code is as follows:
Cnblogswcfclient client = new Cnblogswcfclient ();
Try
{
Client. Dour ("Hello, cnblogs.com!");
Client. Close ();
}
catch (Communicationexception e)
{
...
Client. Abort ();
}
catch (TimeoutException e)
{
...
Client. Abort ();
}
catch (Exception e)
{
...
Client. Abort ();
Throw;
}
The code above is a bit of a shiver, if you don't care what the exception is, as long as the exception is closed, you can use the following code (code from tip:closing your WCF 50x15 properly):
Cnblogswcfclient client = new Cnblogswcfclient ();
Client. Dour ("Hello, cnblogs.com!");
Try
{
if (client. State!= System.ServiceModel.CommunicationState.Faulted)
{
Client. Close ();
}
}
catch (Exception ex)
{
Client. Abort ();
}
Simplified Version Code:
Cnblogswcfclient client = new Cnblogswcfclient ();
Client. Dour ("Hello, cnblogs.com!");
Try
{
Client. Close ();
}
Catch
{
Client. Abort ();
}
Well, the blog has been written, the impression is deeper, the understanding is deeper. Share in the harvest, reap in the share.
Reference articles:
* Avoiding Problems with the Using Statement
* Closing your WCF 50x15 properly