23
15

More than 5 years have passed since last update.

asyncAfterをキャンセルする

Last updated at Posted at 2016-12-11

DispatchWorkItem.cancel()を呼び出すことで、キュー内のまだ実行されていないアイテムの実行を中止できる。

コード

import Cocoa
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true


let workItem = DispatchWorkItem() { Swift.print("not executed") }
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: workItem)
workItem.cancel()

DispatchQueue.main.asyncAfter(deadline: .now() + 1) { Swift.print("executed") }

結果

executed

注意

DispatchWorkItem.cancel()は実行中のアイテムを中断しない。
grand central dispatch - How to stop a DispatchWorkItem in GCD? - Stack Overflow

23
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
15