LoginSignup
1
2

More than 3 years have passed since last update.

【Swift】Grand Central Dispatch (GCD)で処理の途中で手軽にキャンセル処理

Last updated at Posted at 2019-06-25

基本的にはGCDは処理が動いてる途中でCancelできない。
NSOperationを使うのが良いとされている。

しかし、単純な処理についてはGCDを使うのがお手軽なのでキャンセルする方法を考えてみた。

以下、テスト用のプログラムです。

GCDTest.swift
import Foundation

class GCDTest {
    var isCanceled = false
    let grobalQueue = DispatchQueue.global(qos: .userInitiated)
    init() {
        grobalQueue.async {
            var i = 0;
            while(true) {
                if (self.isCanceled) { // 処理の要所に入れる
                    break;
                }
                Thread.sleep(forTimeInterval: 1.0)
                i += 1
                print("\(i)")
            }
            print("Finish GCD")
        }
    }
}

では、上を動かしてみましょう。


    func testGCD() {
        let gcd = GCDTest()
        Thread.sleep(forTimeInterval: 5.0)
        gcd.isCanceled = true
        Thread.sleep(forTimeInterval: 5.0)
        print("Finish test")
    }

結果は以下となります。

1
2
3
4
5
Finish GCD
Finish test

isCanceledをtrueにするとGCDが止まりましたね。

参考:
NSBlockOperationで手軽にキャンセル処理:
https://qiita.com/ninjinkun/items/0fe8548f1debd783a04a

【Swift】Grand Central Dispatch (GCD)とOperationQueue まとめ
https://qiita.com/shiz/items/693241f41344a9df6d6f

1
2
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
1
2