3

I'm writing an HTTP server. There are many like it, but this one is mine. It contains the following code:

 private async void Listen(object state)
 {
      while (webListener.IsListening)
      {
           HttpListenerContext context = await webListener.GetContextAsync();
           Task.Factory.StartNew(() => ProcessRequest(context));
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      }
 }

The code seems to work like a charm. It feels fast, responsive, does not appear to leak resources, etc. However, the line that I have underlined gives a warning in Visual Studio:

Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.

Obviously, the warning goes away if I stick await in front of the Task.Factory.Startnew() ... but does it really make sense to do that in this situation? I want the ProcessRequest to be a "fire and forget" operation, I don't care about any return value, I just want to get back to listening for new requests as quickly as possible.

Should I ignore the warning, or am I missing something?

noseratio
  • 59,932
  • 34
  • 208
  • 486
Ryan Ries
  • 2,381
  • 1
  • 24
  • 33

1 Answers1

3

Well, firstly I'd use Task.Run instead of Task.Factory.StartNew, just for simplicity :)

The next thing is to consider holding onto these tasks not to await them immediately, but so that you can know when they've all finished in order to allow for graceful shutdown.

Basically, if you keep a list of "currently executing tasks" (making sure you clean up after yourself as you go, of course) you can have a "quit" mechanism which allows, say, 10 seconds for all existing requests to complete before shutting the process down. Another thing to consider is adding a continuation on error to each task, so that you can log failures cleanly.

You may well still get similar warnings, but so long as you're thinking about the tasks you're generating, you can suppress or ignore the warning. (So think about it, but don't necessarily change anything.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks for the affirmation that I wasn't just totally missing the point. Also, I have taken your advice and simplified to just `Task.Run` – Ryan Ries Jan 28 '14 at 12:56