effective reuse through dispose in wcf

Posted by deaguero at 2020-04-03

There is no doubt that in the. Net framework, a resource (especially an unmanaged resource) usually needs to implement the IDisposable interface. Once the interface is implemented, we can use the using statement to manage resources, which is the most convenient way. However, once an exception is thrown in the using statement, the resource recovery may not be completed correctly, especially the connection, which is likely to be opened all the time, not only occupying channels and ports, but also wasting resources, thus affecting the performance and stability of the system.

The best practice recommended by Microsoft is to discard the using statement and use the try / catch (/ finally) statement instead. It calls for the Close () method to be invoked in the try statement and the Abort () method in catch. The difference between the close () and abort () methods has been explained in the news, that is, the latter can force the client to close, including closing the client connection and releasing resources. Because the close() method may throw communicationexception and timeoutexception exceptions, the usual client code should be as follows:

In the end, it is necessary to increase the catch of exception exception exception, because we do not know whether the close() method will throw some unpredictable exception, such as OutOfMemoryException, etc. Steve Smith's method mentioned in the news is actually the encapsulation of this lengthy code. The encapsulation method adopts the extension method, and the extension type is icommunicationobject. This is because all client objects implement the icommunicationobject interface. Here is Steve Smith's extension method code:

With this extension method, where the close() method should have been called, instead of the closeconnection() method, lengthy catch code can be avoided. The way of using lambda expression can be said to be a new way, which is close to using syntax. The implementation method is to define a static method and accept an icommunicationobject object and action delegation:

When using, you can pass the original client code as the lambda expression of the action delegate to the using method:

Another way is to define a channelfactory of its own, make it implement the IDisposable interface and act as the wrapper class of channelfactory. When defining the close() and dispose() methods in this class, consider the case of exception throwing, and call the abort() method when the exception is thrown. In this way, we can use the custom channelfactory class in using. For example:

In fact, the way of using agent mode mentioned in the news is the same as this implementation. In a word, the design essence of all alternatives is to package the lengthy try / catch / finally, so as to realize reuse effectively and ensure the safety, performance and stability of the system.