BackgroundService: create task using TaskCreationOptions.LongRunning to prevent thread pool starvation#124608
Conversation
|
Tagging subscribers to this area: @dotnet/area-extensions-hosting |
|
What do you think this is actually improving? |
|
It prevents long-running, blocking I/O operations from occupying ThreadPool worker threads, which could otherwise contribute to ThreadPool starvation under load. In our specific case, the synchronous Consume method of the Confluent Kafka client performs a blocking call. Running this operation on a ThreadPool worker thread risks exhausting available workers when the system is under pressure, potentially impacting request processing and overall application responsiveness. |
|
I don't think we need all background services to pay that cost of spinning up a new thread just in case the code you are using blocks. If you are using the kafka client that is not async then scope that operation by using a thread with blocking APIs. |
Summary
This change updates how the background
ExecuteAsyncmethod is started within theBackgroundService.Previously,
ExecuteAsyncwas launched usingTask.Run, which schedules work on the thread pool. This PR replaces that withTask.Factory.StartNewusingTaskCreationOptions.LongRunningandTaskScheduler.Default.Rationale
TaskCreationOptions.LongRunningsignals that the operation is expected to be long-lived, allowing the runtime to provision a dedicated thread instead of relying on the shared thread pool.ExecuteAsyncruns for the lifetime of the service.ExecuteAsynctask as before.Impact