Simple fix is just check both instead of just deferred in your original process.
But to stop hammering a server unnecessarily, you want no delay when there is active items, some sleep when there is deferred left and exit when everything is done. I'd do it like this:
You don't need to count if "Get Next Item" still returns data, if there is none - you check deferred and sleep if any.
I check unworked too, because checking deferred only might end up with a situation you had. Although unlikely with a 5 sec sleep, it might still happen once in a blue moon.
Stop requested is just something I always add in workqueue scenarios, so that I can safely stop a process without force stopping it inside a lock.
------------------------------
Andrey Kudinov
Project Manager
MobileTelesystems PJSC
Europe/Moscow
------------------------------