0

First off, I know the "correct" answer is don't do background threads in a ASP.NET web app. We have a good reason for doing it this way so please accept the postulate that it makes sense for our use case.

Our background processing is generally CPU bound (can be IO bound at times). And generally will take between 2 seconds and 2 minutes (and occasionally longer, as much as an hour). We will limit the number of background workers to 1.5x the number of cores on the server.

I also assume that it's best to use an existing thread pool in the ASP.NET environment. My code will limit the number of threads, but I'm guessing it's best to pull from the existing pool.

Which then leads to the question, what is the best way to create the threads?

  1. ThreadPool.QueueUserWorkItem
  2. HostingEnvironment.QueueBackgroundWorkItem()
  3. Task.Run()
  4. Something else?

And do HostingEnvironment.QueueBackgroundWorkItem() & Task.Run() come out of the ASP.NET thread pool?

David Thielen
  • 28,723
  • 34
  • 119
  • 193
  • [`QueueUserWorkItem`](https://learn.microsoft.com/en-us/dotnet/api/system.web.hosting.hostingenvironment.queuebackgroundworkitem?view=netframework-4.8) is the only way to register the long-running transaction with the hosting environment so it doesn't kill your threads when the app pool recycles. – John Wu May 14 '20 at 23:05
  • ThreadPool.QueueUserWorkItem is just the older implementation (introduced in .NET 1.1) of doing the same job as Task.Run (introduced in .NET 4.5). See: https://stackoverflow.com/a/38883705/4308286 – Jamshaid K. May 14 '20 at 23:15
  • @JohnWu I thought QueueBackgroundWorkItem() was the only way to delay shutdown until the threads complete? And I believe it only delays for up to 15 seconds. – David Thielen May 15 '20 at 12:16
  • @DavidThielen Ugh yeah I mean QueueBackgroundWorkItem (and that is in fact where my link will take you), I just mistyped. You are correct sir. – John Wu May 15 '20 at 22:53
  • @JohnWu No problem. I appreciate bouncing this stuff off of you. – David Thielen May 16 '20 at 01:04

0 Answers0