public static void CloseAfariaServiceServer(ServerServiceClient svcServer) { try { if (svcServer != null) { // Get the state of the service System.ServiceModel.CommunicationState commState = svcServer.State; // If the service is faulted, we still need to abort if (commState == System.ServiceModel.CommunicationState.Faulted) { svcServer.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 Server.ContextInfo contextInfo = svcServer.GetContextInfo(); // Assure that there is a valid context ID if (!string.IsNullOrWhiteSpace(contextInfo.ContextId)) { // Close the context svcServer.CloseContext(); } // Now close the service svcServer.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. svcServer.CloseContext(); } svcServer = 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 Server service", ex); } }