Handling multiple requests with C# HttpListener

后端 未结 3 2033
执笔经年
执笔经年 2020-11-28 09:12

I have a .NET Windows Service which spawns a thread that basically just acts as an HttpListener. This is working fine in synchronous mode example...

<         


        
相关标签:
3条回答
  • 2020-11-28 09:26

    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 Task.WhenAny(requests);
            requests.Remove(t);
    
            if (t is Task<HttpListenerContext>)
            {
                var context = (t as Task<HttpListenerContext>).Result;
                requests.Add(ProcessRequestAsync(context));
                requests.Add(listener.GetContextAsync());
            }
        }
    }
    
    public async Task ProcessRequestAsync(HttpListenerContext context)
    {
        ...do stuff...
    }
    
    0 讨论(0)
  • 2020-11-28 09:38

    If you need a more simple alternative to BeginGetContext, you can merely queue jobs in ThreadPool, instead of executing them on the main thread. Like such:

    private void CreateLListener() {
        //....
        while(true) {
            ThreadPool.QueueUserWorkItem(Process, listener.GetContext());    
        }
    }
    void Process(object o) {
        var context = o as HttpListenerContext;
        // process request and make response
    }
    
    0 讨论(0)
  • 2020-11-28 09:46

    You need to use the async method to be able to process multiple requests. So you would use e BeginGetContext and EndGetContext methods.

    Have a look here.

    The synchronous model is appropriate if your application should block while waiting for a client request and if you want to process only one *request at a time*. Using the synchronous model, call the GetContext method, which waits for a client to send a request. The method returns an HttpListenerContext object to you for processing when one occurs.

    0 讨论(0)
提交回复
热议问题