Created
January 22, 2012 05:39
-
-
Save stevenkuhn/1655793 to your computer and use it in GitHub Desktop.
Disposing a WCF Proxy Using an Extension Method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class ICommunicationObjectExtensions | |
{ | |
public static void TryCloseOrAbort(this ICommunicationObject obj) | |
{ | |
if (obj != null) | |
{ | |
if (obj.State != CommunicationState.Faulted && | |
obj.State != CommunicationState.Closed) | |
{ | |
try { obj.Close(); } | |
catch (CommunicationObjectFaultedException) | |
{ obj.Abort(); } | |
catch (TimeoutException) | |
{ obj.Abort(); } | |
catch (Exception) | |
{ | |
obj.Abort(); | |
throw; | |
} | |
} | |
else | |
obj.Abort(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example usage: | |
// assume MyServiceClient is a WCF service proxy class | |
var client = new MyServiceClient(); | |
try { client.MyServiceMethod(); } | |
finally { client.TryCloseOrAbort(); } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment