public static void CloseAfariaServiceTenant(TenantServiceClient svcTenant) { try { if (svcTenant != null) { // Get the state of the service System.ServiceModel.CommunicationState commState = svcTenant.State; // If the service is faulted, we still need to abort if (commState == System.ServiceModel.CommunicationState.Faulted) { svcTenant.Abort(); } // If the state is not already closed or in the process of closing, we should close the context else if (commState != System.ServiceModel.CommunicationState.Closing || commState != System.ServiceModel.CommunicationState.Closed) { // Get the context info to get the context ID, although we saved this in the context string variable Tenant.ContextInfo ci = svcTenant.GetContextInfo(); // Assure that there is a valid context ID if (!string.IsNullOrWhiteSpace(ci.ContextId)) { // Close the context svcTenant.CloseContext(); } // Now close the service svcTenant.Close(); } // If the channel is closing/closed, attempt to close out the context, but don't need to close state else { // We will likely throw an exception here. svcTenant.CloseContext(); } svcTenant = null; } } catch (Exception ex) { // Just ouput the exception, proper handling should initiate a new service, initiate the context to the previous, // and then close out the context and service Console.WriteLine(ex.Message.ToString()); logger.Error("Error while closing Tenant service", ex); } }