title: HTTPListener crashes on quad core machine Win 2008 Server R2
body: <p>we created am Exchange Web Service Push Notifications Listener based on the HTTPListener in the EWS book (code below). It ran just fine on a Win 2008 Server with a single core xeon. Now we moved it to a Win 2008 R2 Server with a quad core opteron CPU and it immediately crashes after the Listener is initialized with HTTPListenerExceptions. Now since nothing changed but the Server I thought it might have something to do with multi threading. Maybe someon can advise, thank you.</p>
  
  <pre><code>public class PushNotificationClient
  {
      private uint portNumber;
      private NotificationEventsReceived eventHandler;
      private bool isListening = false;
      private ManualResetEvent stopEvent = new ManualResetEvent(false);
      private bool shouldStop = false;
      private XmlNamespaceManager mgr;
      private XmlSerializer ser;
  
      /// &lt;summary&gt;
      /// Constructor
      /// &lt;/summary&gt;
      /// &lt;param name="portNumber"&gt;Port number to listen on&lt;/param&gt;
      /// &lt;param name="eventHandler"&gt;delegate to call when notifications are
      /// received&lt;/param&gt;
      ///
      public PushNotificationClient(
      uint portNumber,
      NotificationEventsReceived eventHandler)
      {
          this.portNumber = portNumber;
          if (eventHandler == null)
          {
              throw new ArgumentNullException("eventHandler");
          }
          this.eventHandler = eventHandler;
          // namespace manager is used for XPath queries when parsing the request
          //
          this.mgr = new XmlNamespaceManager(new NameTable());
          this.mgr.AddNamespace("t",
          "http://schemas.microsoft.com/exchange/services/2006/types");
          this.mgr.AddNamespace("m",
          "http://schemas.microsoft.com/exchange/services/2006/messages");
          // XmlSerializer is used to convert SendNotification elements into proxy
          // class instances
          //
          this.ser = new XmlSerializer(typeof(SendNotificationResponseType));
      }
  
      /// &lt;summary&gt;
      /// Start Listening
      /// &lt;/summary&gt;
      public void StartListening()
      {
          VerifyNotListening();
          this.stopEvent.Reset();
          this.shouldStop = false;
          // Run the listener on a background thread so we are not blocked
          //
          ThreadPool.QueueUserWorkItem(new WaitCallback(ListenOnThread));
      }
  
      /// &lt;summary&gt;
      /// Stop Listening
      /// &lt;/summary&gt;
      public void StopListening()
      {
          VerifyListening();
          // Set the stopEvent. This will cause the worker thread to close our and
          // dispose of the HttpListener and exit the thread
          //
          this.stopEvent.Set();
      }
  
      /// &lt;summary&gt;
      /// Thread pool method to start listening on the background thread
      /// &lt;/summary&gt;
      /// &lt;param name="state"&gt;State - ignore&lt;/param&gt;
      ///
      private void ListenOnThread(object state)
      {
          using (HttpListener listener = new HttpListener())
          {
              listener.Prefixes.Add(
                  String.Format(
                  "http://+:{0}/PushNotificationsClient/",
                  this.portNumber.ToString()));
              listener.Start();
              this.isListening = true;
              while (!shouldStop)
              {
                  IAsyncResult asyncResult = listener.BeginGetContext(
                  AsyncCallbackMethod, listener);
                  // Wait on either the listener or the stop event
                  //
                  int index = WaitHandle.WaitAny(
                  new WaitHandle[] { stopEvent, asyncResult.AsyncWaitHandle });
                  switch (index)
                  {
                      case 0:
                          // Stop event was triggered.
                          //
                          shouldStop = true;
                          break;
                      case 1:
                          // Notification was received. Just loop around so we can call
                          // BeginGetContext again
                          //
                          break;
                  }
              }
              listener.Stop();
          }
          this.isListening = false;
      }
  
      /// &lt;summary&gt;
      /// Async method called once we receive a request
      /// &lt;/summary&gt;
      /// &lt;param name="result"&gt;Async result containing our HttpListener&lt;/param&gt;
      ///
      private void AsyncCallbackMethod(IAsyncResult result)
      {
          HttpListener listener = result.AsyncState as HttpListener;
          if (!this.isListening)
          {
              // Our callback gets fired when we stop the listener too. If it is not
              // listening, just return.
              //
              return;
          }
          HttpListenerContext context = listener.EndGetContext(result);
          SendNotificationResponseType request;
          // Now use the XML serializer to turn the XML into a notification
          // serialization type...
          //
          XmlDocument doc = new XmlDocument();
          try
          {
              doc.LoadXml(
              new StreamReader(
              context.Request.InputStream).ReadToEnd());
              // retrieve the first SendNotification element (there should be only one).
              //
              XmlNodeList nodes = doc.SelectNodes("//m:SendNotification[1]", this.mgr);
              if (nodes.Count == 0)
              {
                  // this wasn't a SendNotification request or it was malformed or
                  // something like that.
                  FailRequest(context);
                  return;
              }
              string sendNotification = nodes[0].OuterXml;
              using (MemoryStream ms = new MemoryStream())
              {
                  byte[] bytes = Encoding.UTF8.GetBytes(sendNotification);
                  ms.Write(bytes, 0, bytes.Length);
                  ms.Flush();
                  ms.Position = 0L;
                  request = (SendNotificationResponseType)this.ser.Deserialize(ms);
              }
          }
          catch (XmlException)
          {
              // Failed to deserialize request.
              //
              FailRequest(context);
              return;
          }
          // Fire the delegate
          //
          NotificationResponse response = eventHandler(
          this, /* sender */
          request.ResponseMessages.Items[0]
          as SendNotificationResponseMessageType);
          GenerateResponseXML(context, response);
      }
  
      /// &lt;summary&gt;
      /// Fail the request. Right now we don't differentiate between reasons why it
      /// failed.
      /// &lt;/summary&gt;
      /// &lt;param name="context"&gt;Request context&lt;/param&gt;
      ///
      private void FailRequest(HttpListenerContext context)
      {
          context.Response.ContentEncoding = Encoding.UTF8;
          context.Response.ContentType = "text/xml; charset=utf-8";
          context.Response.ProtocolVersion = new Version(1, 1, 0, 0);
          context.Response.StatusCode = 400;
          string response = "&lt;?xml version=\"1.0\"?&gt;" +
          "&lt;Error&gt;Bad Request&lt;/Error&gt;";
          byte[] responseBytes = Encoding.UTF8.GetBytes(response);
          context.Response.ContentLength64 = responseBytes.Length;
          context.Response.OutputStream.Write(
          responseBytes, 0, responseBytes.Length);
          context.Response.OutputStream.Flush();
      }
  
      /// &lt;summary&gt;
      /// Generate the response xml
      /// &lt;/summary&gt;
      /// &lt;param name="context"&gt;call context&lt;/param&gt;
      /// &lt;param name="response"&gt;The response enum value&lt;/param&gt;
      ///
      private void GenerateResponseXML(
      HttpListenerContext context,
      NotificationResponse response)
      {
          StringBuilder builder = new StringBuilder();
          builder.AppendLine("&lt;?xml version=\"1.0\"?&gt;");
          builder.AppendLine("&lt;s:Envelope xmlns:s= " +
          "\"http://schemas.xmlsoap.org/soap/envelope/\"&gt;");
          builder.AppendLine("&lt;s:Body&gt;");
          builder.AppendLine(" &lt;SendNotificationResult " +
          "xmlns=\"http://schemas.microsoft.com/exchange/services/2006/messages\"&gt;");
          builder.AppendFormat(" &lt;SubscriptionStatus&gt;{0}&lt;/SubscriptionStatus&gt;\r\n",
          response.ToString());
          builder.AppendLine(" &lt;/SendNotificationResult&gt;");
          builder.AppendLine("&lt;/s:Body&gt;");
          builder.AppendLine("&lt;/s:Envelope&gt;");
          context.Response.ContentEncoding = Encoding.UTF8;
          context.Response.ContentType = "text/xml; charset=utf-8";
          context.Response.ProtocolVersion = new Version(1, 1, 0, 0);
          context.Response.StatusCode = 200;
          byte[] responseBytes = Encoding.UTF8.GetBytes(builder.ToString());
          context.Response.ContentLength64 = responseBytes.Length;
          context.Response.OutputStream.Write(
          responseBytes, 0, responseBytes.Length);
          context.Response.OutputStream.Flush();
      }
  
      /// &lt;summary&gt;
      /// Returns true if the listener is listening
      /// &lt;/summary&gt;
      public bool IsListening
      {
          get
          {
              return isListening;
          }
      }
      /// &lt;summary&gt;
      /// Verifies that the listener isn't listening
      /// &lt;/summary&gt;
      private void VerifyNotListening()
      {
          if (isListening)
          {
              throw new PushNotificationStateException("Cannot perform this operation " +
              "when listening");
          }
      }
  
      /// &lt;summary&gt;
      /// Verifies that the listener is listening
      /// &lt;/summary&gt;
      private void VerifyListening()
      {
          if (!isListening)
          {
              throw new PushNotificationStateException("Cannot perform this operation " +
              "when not listening");
          }
      }
  
  
  }
  </code></pre>