In the previous article (what will happen if the service agent can't be shut down in time?), we talked about the importance of the timely shutdown of service proxies in a high concurrency environment, and clarified its root causes. However, is it all right to call the Icommunicationobject Close method directly to shut down the service proxy? It's not that simple, it's going to involve some manipulation of exception handling, which is what this article needs to discuss.
One, the exception throws with the failure of close
In general, when the service side throws an exception, the service proxy for the client client cannot be shut down directly, and WCF throws an exception during the Close method execution. We can confirm this by using the example below. In this example, we still follow the example of a compute service, which is the definition of a service contract and a service implementation:
1:using System.ServiceModel;
2:namespace Artech.ExceptionHandlingDemo.Contracts
3: {
4: [ServiceContract (Namespace = "urn:artech.com")]
5: Public interface ICalculator
6: {
7: [OperationContract]
8: int Divide (int x, int y);
9: }
10:}
1:using System;
2:using System.ServiceModel;
3:using Artech.ExceptionHandlingDemo.Contracts;
4:namespace Artech.ExceptionHandlingDemo.Services
5: {
6: class Calcualtorservice:icalculator {public int Divide (int x, int y) {return x/y;}}
7:}
In order to ensure the timely shutdown of the service agent, according to the typical programming method, we need to use the try/catch/finally way to operate the service proxy object, and the service agent shutdown in the finally block. The calling program for the WCF service at the client is as follows:
1:using System;
2:using System.ServiceModel;
3:using Artech.ExceptionHandlingDemo.Contracts;
4:namespace Client
5: {
6:class program
7: {
8:static void Main (string[) args)
9: {
10:using (channelfactory<icalculator> channelfatory = new ChannelFactory <ICalculator> (New Wshttpbinding (), "Http://127.0.0.1:3721/calculatorservice")
One: {
12: ICalculator calcultor = Channelfatory.createchannel (); Try
: {
14:calcultor. Divide (1, 0);
15:}
16:catch (Exception ex) {Console.WriteLine (ex. message);
17:finally
: {
: Calcultor as Icommunicationobj ECT). Close ();
20:}
21:}
22:}
23:}
:}
Because the parameters passed in are 1 and 0, the Dividedbyzero exception is thrown when the service performs a division operation. When the service-side program executes to the finally block to close the service proxy, it throws the following Communicationobjectfaultedexception exception, which prompts the Serivcechannel state to be faulted, cannot be used for subsequent communication.