Use lambda expressions to properly close the WCF connection

Source: Internet
Author: User

Address: http://www.cnblogs.com/ILoveSleep/archive/2013/06/11/3132085.html

 

WCF is a good thing! It is easy to use, has powerful functions, and has a large scalability. However, there is also a flaw in the concept of WCF:

How can I close the WCF connection correctly on the client!

If you directly close the client call or use the using statement, it will be a tragedy. I believe that the comrades who use WCF know this, because the close () of the clientbase class () after a method is called, a network session is actually closed and an exception is thrown!Communicationexception andTimeoutexception!

This seems to be against common sense, but it does happen. Generally, the close function does not throw an exception. The solution to this problem is to use the try-catch statement to include the close () method, and then use the abort function to release resources during exception handling!

Similarly, the implementation function of the idisposable interface of the clientbase class dispose method calls the close function and uses reflector to viewCodeZhizhi

Therefore, you cannot close the WCF connection correctly using the using statement! However, we use the using statement to release relevant resources no matter what happens, as long as it leaves the scope. The clientbase class design of WCF is a clear violation of this concept! It's just a pitfall!

There are many solutions to solve this problem on the Internet. First, let's talk about Microsoft. Maybe Microsoft is aware of this, so the WCF example provided by MicrosoftProgramIt contains an example called usingusing. The name sounds strange.

The main solution is the following code:

 1   //  This method shows the correct way to clean up a client, including catching  2           //  Approprate exceptions.  3           Static   Void Demonstratecleanupwithexceptions () 4 { 5               //  Create a client  6 Calculatorclient client = New Calculatorclient (); 7              Try  8 { 9                   //  Demonstrate a successful client call.  10 Console. writeline ( "  Calling client. Add (0.0, 0.0 );  " ); 11                   Double Addvalue = client. Add ( 0.0 , 0.0 ); 12 Console. writeline ( "  Client. Add (0.0, 0.0); returned {0}  " , Addvalue ); 13   14                   //  Demonstrate a failed client call. 15 Console. writeline ( "  Calling client. Divide (0.0, 0.0 );  " ); 16                   Double Dividevalue = client. Divide ( 0.0 , 0.0 ); 17 Console. writeline ( "  Client. Divide (0.0, 0.0); returned {0}  " , Dividevalue ); 18   19                   //  Do a clean shutdown if everything works. In this sample we do not end up  20                   // Here, but correct code shoshould close the client if everything was successful.  21 Console. writeline ( "  Closing the client  " ); 22 Client. Close (); 23 } 24               Catch (Communicationexception E) 25 { 26                   //  Because the server suffered an internal server error, it rudely terminated  27                   //  Our connection, so we get a communicationexception.  28 Console. writeline ("  Got {0} from divide.  " , E. GetType ()); 29 Client. Abort (); 30 } 31               Catch (Timeoutexception E) 32 { 33                   //  In this sample we do not end up here, but correct code shocould catch  34                   //  Timeoutexception when calling a client.  35 Console. writeline ( "  Got {0} from divide.  " , E. GetType ()); 36 Client. Abort ();37 } 38               Catch (Exception E) 39 { 40                   //  In this sample we do not end up here. It is best practice to clean up  41                   //  Client if some unexpected exception occurs.  42 Console. writeline ( "  Got unexpected {0} from divide, rethrowing.  " , E. GetType ()); 43 Client. Abort (); 44                   Throw ; 45 } 46 }

In fact, it is to use the try-catch statement to catch exceptions when closing! Imagine how painful it would be to call the WCF Service like this every time! Some people also use the expression of LINQ to solve this problem on the Internet.

So I borrowed the idea of functional programming and designed a solution to solve this problem using lambda expressions!

The key functions are simple. You can see how I designed them!

 1   Public   Static   Class Svcclient 2 { 3           Public   Static   Void Invoke <tclient> (Action <tclient> Act) 4               Where Tclient: system. servicemodel. icommunicationobject, New () 5 { 6 Tclient client = New Tclient (); 7               Try  8 { 9 Act (client ); 10 Client. Close (); 11 } 12               Catch (System. servicemodel. communicationexception) 13 { 14 Client. Abort (); 15 } 16               Catch (Timeoutexception) 17 { 18 Client. Abort (); 19 } 20               Catch (Exception) 21 { 22 Client. Abort (); 23                   Throw ; 24 } 25 } 26 }

In fact, the idea of this design is to pass in all the code that calls the WCF Service as a function, and then I use the try-catch statement internally to wrap the entire call process, in this way, the code that handles the disconnection exception is cleverly separated from the actual call process!

It is also convenient to use functions.

 
1Svcclient. Invoke <service1client> (client =>2{3//Add the code for calling WCF here4});

The code looks concise and elegant, and I am quite satisfied with myself. I don't have to worry about closing the WCF connection after the call is complete, and the resources cannot be released correctly!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.