i'm trying to create a HttpListener
and accept Http request, for each HttpListenerContext
i create a dedicated thread to do work on it like this
while(true)
{
var context = listener.GetContext();
Thread backgroundThread = new Thread(() => HandleContext(context));
backgroundThread.Start();
}
In the HandleContext
i do a Thread.Sleep(5000)
to simulate the work and Console.WriteLine(DateTime.Now)
for debugging purpose.
But when i open 3 tabs in Chrome at the same time, only 2 tabs return but the result is duplicated and the last tab just keep hanging.
As far as i know, my threads has no shared data which could lead to deadlock, but this behavior seems like a deadlock, can you tell me what i'm doing wrong and how to fix it?
Here's my full code
class Program
{
private static HttpListener _listener;
static void Main(string[] args)
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:5001/");
listener.Start();
Listen(listener);
}
static void Listen(HttpListener listener)
{
while (true)
{
var context = listener.GetContext();
Thread backgroundThread = new Thread(() => HandleContext(context));
backgroundThread.Start();
}
}
static void HandleContext(HttpListenerContext context)
{
Thread.Sleep(5000);
Console.WriteLine($"Hello world, {DateTime.Now}");
var responseContent = "Hello world";
var buffer = Encoding.UTF8.GetBytes(responseContent);
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
context.Response.OutputStream.Close();
context.Response.Close();
}
}
CodePudding user response:
You didn't set the ContentLength64
property of your HttpListenerResponse
stream !
Please try this
context.Response.ContentLength64 = buffer.LongLength;
using (Stream stream = context.Response.OutputStream)
{
stream.Write(buffer, 0, buffer.Length);
}
CodePudding user response:
After a while, i figured out that the "deadlock" like behavior occurred because of the "orphan" GetContext
which @Mat Hatter pointed out. And the Console.WriteLine being duplicated because of Google Chrome's behavior sending 2 requests, 1 for the website's content and 1 for the fav.icon. Hence, there's nothing wrong with the Console.WriteLine being duplicated.