Multi-threading with .Net HttpListener

For completeness, here is what it would look like if you manage your own worker threads: class HttpServer : IDisposable { private readonly HttpListener _listener; private readonly Thread _listenerThread; private readonly Thread[] _workers; private readonly ManualResetEvent _stop, _ready; private Queue<HttpListenerContext> _queue; public HttpServer(int maxThreads) { _workers = new Thread[maxThreads]; _queue = new Queue<HttpListenerContext>(); _stop = … Read more

Handling multiple requests with C# HttpListener

If you’re here from the future and trying to handle multiple concurrent requests with a single thread using async/await.. public async Task Listen(string prefix, int maxConcurrentRequests, CancellationToken token) { HttpListener listener = new HttpListener(); listener.Prefixes.Add(prefix); listener.Start(); var requests = new HashSet<Task>(); for(int i=0; i < maxConcurrentRequests; i++) requests.Add(listener.GetContextAsync()); while (!token.IsCancellationRequested) { Task t = await … Read more

Httplistener with HTTPS support

I did a bunch of homework and got this working. The steps to add SSL support for an .NET HttpListener are: Update C# application code to include the https prefix. Example: String[] prefixes = { “http://*:8089/”,”https://*:8443/” }; That’s it from the code aspect. For the certificate side of things, using the Windows SDK command console … Read more