Do I need to close a .NET service reference client when I'm done using it

后端 未结 3 1473
耶瑟儿~
耶瑟儿~ 2021-02-01 21:05

I\'m trying to find out if it is neccessary to close a .net service reference client when you are done using it. Almost all of the examples that I have come across on the net d

3条回答
  •  渐次进展
    2021-02-01 21:57

    Yes, you do, but you need to be very careful when doing so. While closing anything that implements ICommunicationObject the potential exists to cause the disposal of the object to take an excessive amount of time in the event that there is an error or fault on the channel.

    Because of this, it is prescribed that you call the Close method and then call the Dispose method on IDisposable, using a number of catches for certain exception types and calling Abort before you finally call Dispose.

    You can wrap this logic up in an IDisposable implementation which you can use in a using statement.

    The key here is to create a token that implements IDisposable and then in that implementation, call Close, catch the relevant exceptions, call Abort (if necessary) and then call Dispose.

    This is implemented as an extension method which returns an IDisposable on it which in turn allows you to use it in a using statement.

提交回复
热议问题