Skip to content

Instantly share code, notes, and snippets.

@cbalioglu
Created March 17, 2015 17:31
Show Gist options
  • Save cbalioglu/9776fd4fe24288975270 to your computer and use it in GitHub Desktop.
Save cbalioglu/9776fd4fe24288975270 to your computer and use it in GitHub Desktop.
An extension method for ICommunicationObject derived WCF types that enables exception-safe disposal.
using System;
using System.ServiceModel;
namespace Balioglu
{
public static class ICommunicationObjectExtensions
{
/// <summary>
/// Closes or aborts the specified communication object depending on its state without
/// throwing an exception.
/// </summary>
public static void SafeDispose(this ICommunicationObject communicationObject)
{
if (communicationObject == null)
{
throw new ArgumentNullException("communicationObject");
}
if (communicationObject.State == CommunicationState.Faulted)
{
communicationObject.Abort();
}
else
{
try
{
communicationObject.Close();
}
catch (CommunicationException)
{
communicationObject.Abort();
}
catch (TimeoutException)
{
communicationObject.Abort();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment