Skip to content

Instantly share code, notes, and snippets.

@stevenkuhn
Created January 22, 2012 05:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevenkuhn/1655793 to your computer and use it in GitHub Desktop.
Save stevenkuhn/1655793 to your computer and use it in GitHub Desktop.
Disposing a WCF Proxy Using an Extension Method
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();
}
}
}
// 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