title: Wrap `HttpListener`'s `GetContextAsync()`
body: <p>I'm trying to wrap the <code>HttpListener</code> class and added more logic which deals with Web Sockets.</p>
  
  <p>Finally, I'm trying to wrap the <code>GetContextAsync()</code> method to only return <code>HttpListenerContext</code> objects which are web sockets.</p>
  
  <p>So far I have:</p>
  
  <pre><code>public Task&lt;HttpListenerContext&gt; GetContextAsync()
  {
      Task&lt;HttpListenerContext&gt; contextTask = listener.GetContextAsync();
      if (contextTask.Result.Request.IsWebSocketRequest)
      {
          return contextTask;
      }
      else
      {
          contextTask.Result.Response.StatusCode = 500;
          contextTask.Result.Response.Close();
          return GetContextAsync();
      }
  }
  </code></pre>
  
  <p>But When I call the outer function (of the wrapper class), using:</p>
  
  <pre><code>HttpListenerContext listenerContext = await listener.GetContextAsync();
  </code></pre>
  
  <p>The <code>await</code> won't return to the main thread until a first connection is achieved.</p>
  
  <hr>
  
  <h3>EDIT</h3>
  
  <p>If it helps someone, I ended up going with the following:</p>
  
  <pre><code>public async Task&lt;HttpListenerContext&gt; GetContextAsync()
  {
      HttpListenerContext listenerContext = await listener.GetContextAsync();
      while (!listenerContext.Request.IsWebSocketRequest)
      {
          listenerContext.Response.StatusCode = 500;
          listenerContext.Response.Close();
          listenerContext = await listener.GetContextAsync();
      }
      return listenerContext;
  }
  </code></pre>