Handling multiple requests with C# HttpListener

后端 未结 3 2061
执笔经年
执笔经年 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();
        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)
            {
                var context = (t as Task).Result;
                requests.Add(ProcessRequestAsync(context));
                requests.Add(listener.GetContextAsync());
            }
        }
    }
    
    public async Task ProcessRequestAsync(HttpListenerContext context)
    {
        ...do stuff...
    }
    

提交回复
热议问题