-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Description
Is there an existing issue for this?
- I have searched the existing issues
Description
A long-running background job following the doc cannot be canceled when run.

Figure: Pressing Control+C failed to terminate the running app
Reproduction Steps
A minimal console app to reproduce: BackgroundJobTest.zip
- Decompress the zip file
dotnet runto start the app- Wait till see log output "Waiting for ctrl+c cancellation..." and press Control+C
- Observe log output indicating the app is shutting down but the background job keeps running
Expected behavior
Cancel signal (Control+C) terminates the app and the running background job, if the job properly handles CancellationToken
Actual behavior
Cancel signal is unable to terminate the background job (see screenshot and repro steps above)
Regression?
Unknown
Known Workarounds
It seems to be caused by
- AsyncPeriodicBackgroundWorkerBase.StartCancellationToken is set to an unused token instance, code reference
- BackgroundWorkerBase.StoppingTokenSource is canceled after Timer.Stop, which creates a deadlock where the timer is waiting for the job to finish while the job is waiting for the cancel request from
StoppingTokencode reference
By creating a custom BackgroundJobWorker replacing the original one and overriding the behaviours above, I managed to fix this issue and achieve a graceful terminate.
However I'm not absolutely certain that this is the right fix so not putting my workaround code here for simplicity.
Version
9.2.1
User Interface
Common (Default)
Database Provider
None/Others
Tiered or separate authentication server
None (Default)
Operation System
macOS
Other information
No response