There is a task to write a simple HTTP server. All the examples that I met looked something like this:

while (true) { var context == listener.GetContext(); Task.run(() => HandleContext(context)); } 

Well, ok, but then why do you need HTTPListener.GetContextAsync () ;? Suppose if it were like this:

 while (true) { var context = await listener.GetContextAsins(); Task.run(() => HandleContext(context)); } 

However, as far as I can tell, this is the same. I would be very grateful for an explanation of how to use this method to get some profit.

  • I suspect it is needed so that it can be await from the inside of the task. - arrowd

1 answer 1

This is a wrapper over calls to BeginGetContext / EndGetContext . They serve to access the asynchronous API, which allows the use of I / O Completion Portes.

Here is a little bit of the story: https://stackoverflow.com/questions/4577193/using-httpapi-with-io-completion-ports

If it is very rough, then these are operating system tools that allow you not to hold the workflow while waiting for a client request / server response, etc. If you run 10,000 concurrent calls to GetContext (), they will spawn 10,000 pending threads. In the case of using Async I / O, additional threads will be generated only at the time of receiving a response from the remote side, which will greatly facilitate the life of a highly loaded server.

  • Thank you, but I would like to clarify: I correctly understand that a function should be called in a loop, in which GetContextAsync () will already be called in turn? And yet, GetContextAsync is most relevant for highly loaded servers, and if it is not assumed that the server will be very loaded, then there is no point in using it? More precisely not so, is there any sense not to use it? That is, it is always better to use asynchronous methods by default or in some cases it may be undesirable or even harmful? - Konstantin Galiakhmetov
  • In the example that you cited, the await construct is used, which designates the following code as a continuation. This way you get rid of the need to manually control callbacks. Therefore, yes, both of your examples are true. If you built calls on the basis of Begin / End, then in the handler you would call End first, and then immediately Begin, so that before you handle the current call, the server starts listening to the next one. Naturally, any asynchronous calls contribute overhead. But the synchronous server is subject to various attacks, including DoS. - Albeoris