Search code examples
c#winformsbackgroundworkerbackground-process

How to kill a BackgroundWorker process when it is waiting for an external event


I have a BackgroundWorker process created this way:

_worker = new BackgroundWorker();
_worker.WorkerSupportsCancellation = true;
_worker.DoWork += WaitForCard;
_worker.RunWorkerAsync();

The worker process is calling an API for smart card (for instance it is SCardGetStatusChange function API). That call blocks execution until a card is placed on a reader.

The problem is when I close the Winform application. I am using:

    _worker.CancelAsync();
    _worker.Dispose();

The worker process set its CancellationPending property to true and the main form closes, however, application does not actually exit because the worker process is still waiting for the external input.

How to finish the working process even when it is waiting for an external input?


Solution

  • EDIT: To force the SCardGetStatusChange function to cancel, use SCardCancel: https://msdn.microsoft.com/en-us/library/windows/desktop/aa379470(v=vs.85).aspx