Handling cancellation and shutdown