title: Async httpListener is the callback initiated on the UI thread?
body: <p>I am looking to build an httpListener into a small server app. Whilst reading up on it, i encountered the following code snippet in <a href="https://stackoverflow.com/questions/6907841/httplistener-performance-optimization">this question on stackoverflow</a></p>
  
  <pre><code>Public Class HTTPServer
  
  Shared Listener As HttpListener = New HttpListener
  
  Public Shared Sub Start()
  
      ServicePointManager.DefaultConnectionLimit = 500
      ServicePointManager.Expect100Continue = False
      ServicePointManager.MaxServicePoints = 500
  
      Listener.Prefixes.Add("http://localhost/")
      Listener.Start()
  
      For i As Integer = 1 To (System.Environment.ProcessorCount * 2)
  
          Dim NewThread As New System.Threading.Thread(AddressOf ListenerThread)
          NewThread.Priority = ThreadPriority.Normal
          NewThread.IsBackground = True
          NewThread.Start()
  
      Next
  
  End Sub
  
  
  
  Private Shared Sub ListenerThread()
  
      Dim SyncResult As IAsyncResult
  
      While True
  
          SyncResult = Listener.BeginGetContext(New AsyncCallback(AddressOf ListenerCallback), Listener)
          SyncResult.AsyncWaitHandle.WaitOne()
  
      End While
  
  End Sub
  
  
  
  Private Shared Sub ListenerCallback(ByVal StateObject As IAsyncResult)
  
      Dim Listener As HttpListener = DirectCast(StateObject.AsyncState, HttpListener)
  
      Dim Context As HttpListenerContext = Listener.EndGetContext(StateObject)
      Dim Request As HttpListenerRequest = Context.Request
  
      Dim Response As HttpListenerResponse = Context.Response
  
      Dim ResponseString As String = "OK"
  
      Dim Buffer As Byte() = System.Text.Encoding.UTF8.GetBytes(ResponseString)
      Response.ContentLength64 = Buffer.Length
      Dim OutputStream As System.IO.Stream = Response.OutputStream
      OutputStream.Write(Buffer, 0, Buffer.Length)
  
      OutputStream.Close()
      OutputStream.Dispose()
  
  End Sub
  
  End Class
  </code></pre>
  
  <p>Which seemed pretty simple, and seems much like the <a href="http://msdn.microsoft.com/en-us/library/system.net.httplistener.begingetcontext.aspx" rel="nofollow noreferrer">msdn example</a>. However when testing it in a dummy project, i found a few things that confused me, for example UI objects can be accessed directly from the callback sub, which i thought should cause a cross threading exception.</p>
  
  <p>To clarify, i modified this code slightly to run within the main form of a simple winforms project.</p>
  
  <p>It seems i do not fully understand the code, for example AsyncWaitHandle.WaitOne() is completely new to me.</p>
  
  <p>Could someone briefly walk me through this snippet please? Any help appreciated.</p>