title: WCF Wait for operations to finish when closing ServiceHost
body: <p>I create a WCF SOAP server with an operation that takes some time to perform:</p>
  
  <pre><code>[ServiceContract]
  public interface IMyService
  {
      [OperationContract]
      string LongRunningOperation();
  }
  
  [ServiceBehavior(
      ConcurrencyMode = ConcurrencyMode.Multiple,
      UseSynchronizationContext = false,
      InstanceContextMode = InstanceContextMode.Single)]
  class MyService : IMyService
  {
      public string LongRunningOperation()
      {
          Thread.Sleep(20000);
          return "Hey!";
      }
  }
  
  class Program
  {
      static void Main(string[] args)
      {
          MyService instance = new MyService();
          ServiceHost serviceHost = new ServiceHost(instance);
          BasicHttpBinding binding = new BasicHttpBinding();
          serviceHost.AddServiceEndpoint(typeof(IMyService), binding, "http://localhost:9080/MyService");
          serviceHost.Open();
          Console.WriteLine("Service running");
          Thread.Sleep(10000);
          serviceHost.Close();
          Console.WriteLine("Service closed");
          Thread.Sleep(30000);
          Console.WriteLine("Exiting");
      }
  }
  </code></pre>
  
  <p>The ServiceHost is opened, and after 10 seconds I close it.</p>
  
  <p>When calling serviceHost.Close(), all clients currently connected, waiting for <em>LongRunningOperation</em> to finish, are inmediately disconnected.</p>
  
  <p>Is there a wait of closing the ServiceHost in a cleaner way? That is, I want to disable the service listeners, but also wait for all currently connected clients to finish (or specify a maximum timeout).</p>