I am struggling with HttpListener
and awaiting its context. Sometimes I am really confused. I have the application to run this server. However, I don't want to await the requests. I want to run server in a background and don't care about it. But I am not sure if it is a good idea, because Microsoft says that if you have something like an I/O operation it should be awaited. But I don't want to await it. What if I want to write something in my console? I cannot, because I await HttpListener's context. The solution looks pretty simple:
// _server is an instance of HttpListener
public void StartServer()
{
_server.Prefixes.Add("http://127.0.0.1:8080/test/");
_server.Start();
Task.Run(async() =>
{
while (_server.IsListening)
{
HttpListenerContext context = await _server.GetContextAsync();
await HandleContextAsync(context);
}
}).ConfigureAwait(false);
}
However, in this case I am not sure that there won't be any deadlocks or something, because handling the context requires a lot of operations (for example, it opens a DB connection somewhere).
The last thing I have decided to do is to separate my main application and the server side, but I still want to run server in the background to be able to stop it using some input from the console. What should I do?
I've also tried something like this:
Task serverListener = server.StartServerAsync();
Console.ReadLine();
await server.StopServerAsync();
//
// The server methods:
//
public async Task StartServerAsync()
{
_server.Prefixes.Add("http://127.0.0.1:8080/test/");
_server.Start();
while (_server.IsListening)
{
HttpListenerContext context = await _server.GetContextAsync();
await HandleContextAsync(context);
}
}
public Task StopServerAsync()
{
_server.Stop();
_server.Close();
return Task.CompletedTask;
}
But in this case I am not sure what happens with Task, because it is not cancelled or something. The server has been stopped, but the Task is still awaitable. Is it better than the first case with Task.Run()
or not?