Skip to content

Unable to cancel background job #23205

@jimmidier

Description

@jimmidier

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.

Image
Figure: Pressing Control+C failed to terminate the running app

Reproduction Steps

A minimal console app to reproduce: BackgroundJobTest.zip

  1. Decompress the zip file
  2. dotnet run to start the app
  3. Wait till see log output "Waiting for ctrl+c cancellation..." and press Control+C
  4. 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

  1. AsyncPeriodicBackgroundWorkerBase.StartCancellationToken is set to an unused token instance, code reference
  2. 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 fromStoppingToken code 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

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions