0

I have a game where I am creating a pause button. The pause button needs to stop and then resume a specific task:

DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: {
        if self.ongoing {
            self.dispose()
        }
})

I was thinking of doing this by keeping track of when this task was scheduled and keeping track of when the pause started so I could then schedule a new task with an updated time after the player unpauses. However, I don't know how to cancel the old task. Is there an easier way of freezing/stopping temporarily a task scheduled by DispatchQueue?

Pablo
  • 1,302
  • 1
  • 16
  • 35
  • Hope this help https://stackoverflow.com/questions/29492707/how-to-stop-cancel-suspend-resume-tasks-on-gcd-queue – Quoc Nguyen Apr 04 '18 at 00:46
  • You don’t `suspend` tasks. You `suspend` private queues which prevents anything from starting on that queue (but does nothing with tasks already running on that queue). I am hard-pressed to imagine using GCD queues for your use-case. Sure, if you’re already using queues to manage the state of your app (e.g. dispatch timers), fine, but personally I’d be inclined to pursue non-GCD solutions for this. – Rob Apr 04 '18 at 02:31

1 Answers1

1

If the task has already been launched, the easiest way to do this is to have an isCancelled variable that your task's code repeatedly checks inside its main loop. To cancel the task, you simply set the isCancelled variable to true. You may want to use a lock and/or semaphore to make the variable thread-safe. If you use OperationQueue instead of DispatchQueue, the Operation object contains an isCancelled operation which is ready-made for this purpose (and if you manage to set the isCancelled property before the operation has even started, OperationQueue will skip running it at all).

Charles Srstka
  • 16,665
  • 3
  • 34
  • 60
  • 1
    FYI, `DispatchWorkItem` already has an [`isCancelled`](https://developer.apple.com/documentation/dispatch/dispatchworkitem/1780829-iscancelled) property. You can then [`cancel`](https://developer.apple.com/documentation/dispatch/dispatchworkitem/1780910-cancel) the `DispatchWorkItem` and that existing `isCancelled` property will be set for you. – Rob Apr 04 '18 at 02:24
  • @Rob That is quite nice; I wasn't aware of that. – Charles Srstka Apr 04 '18 at 02:30