void listenerCallback(IAsyncResult httpResult) { var listener = (HttpListener)httpResult.AsyncState; var context = listener.EndGetContext(httpResult); var request = context.Request; var response = context.Response; listener.BeginGetContext(listenerCallback, listener); string requestBody = null; string responseString = ""; response.ContentType = "application/json"; try { if (request.HttpMethod.ToUpper() == "POST" && request.HasEntityBody) { using (var reader = new StreamReader(request.InputStream, request.ContentEncoding)) { requestBody = reader.ReadToEnd(); } } var task = worker.AddTask(new RequestInfo(context, requestBody, this)); task.WaitForResponse(); if (task.State == ThreadTask <RequestInfo> .ThreadTaskState.Error) { responseString += $"Error when invoking:\n{task.Error}"; } else { responseString += task.Response.Response; } } catch (Exception e) { responseString += $"Error when processing:\n{e}"; } sendResponse(response, responseString); }