1

In my Web Api 2 method I'm doing some work and then I need to hit another site's REST endpoint, so I'm using HttpWebRequest to send the message. However, that external URL is going to process for 30 minutes before it returns (I don't own the external site). I don't want the caller of my method to have to wait for that return to complete.

Besides the obvious "if the other site fails you don't know" is there any downside to not doing an await on the request.GetResponseAsync() method and just letting my code return?

Gargoyle
  • 9,590
  • 16
  • 80
  • 145
  • Probably answered under https://stackoverflow.com/q/12803012/11683. – GSerg Apr 19 '19 at 17:26
  • @GSerg That seems to be saying use Task.Run() which is also an async awaitable method which I'd leave the await off of. Is there any advantage to that? – Gargoyle Apr 19 '19 at 17:54
  • While the linked article is valid, if you're replace the "forget" bit with "monitor" there's no harm in that. So _if you're able to_, instead of awaiting it, save the returned Task, and in some way come back to it later and await it then. Whether that is feasible in your app only you will know. BTW a sync HTTP call lasting 30 minutes is just silly. Can't they reply with a 202 and a Location header where you can monitor progress instead? – sellotape Apr 19 '19 at 18:02

1 Answers1

2

is there any downside to not doing an await

Possibly. When your local HttpWebRequest is disposed, it will probably notify the remote API, which is generally interpreted as a "cancel" by web servers. Your local HttpWebRequest could be finalized when your app is unloaded/recycled, which happens periodically on ASP.NET/IIS.

For this reason, I would recommend a standard queue-with-independent-backend solution for this: have your API place the request in a queue, and have a separate backend process do the long-running API calls.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • I'm not entirely following. The Web API 2 controller is created per request, so I can't hold a queue somewhere. Are you just saying to do the Task.Run() and not await it? – Gargoyle Apr 19 '19 at 20:11