void GetContext(IAsyncResult ar, CancellationToken token) { IHttpContext context; try { var listenerContext = _listener.EndGetContext(ar); context = new HttpListenerContextAdapter(_environment, listenerContext); if (!token.IsCancellationRequested) { // setup the next request _listener.BeginGetContext(_ => GetContext(_, token), null); } } catch (InvalidOperationException) { // stopping probably return; } catch (HttpListenerException) { // stopping probably return; } if (false == _requestSemaphore.Wait(TimeSpan.FromSeconds(3))) { HandleTooBusyError(context); return; } try { ProcessRequestInner(context); } finally { _requestSemaphore.Release(); } }