Skip to content

비동기 취소 예시 코드

In Ye, Kim edited this page Jan 10, 2025 · 1 revision

취소가 '전파'만 되는 것을 확인해볼 수 있는 예시

Swift Concurrency

import Foundation

func testSleep() async {
    print("시작")
    sleep(4)
    print("종료")
}

var task: Task<Void, Never>?

task = Task {
    print("-----진짜 시작-----")

    await testSleep()
    await testSleep()
    await testSleep()
    
    print("-----완전 종료-----")
}

sleep(3)
task?.cancel()

RunLoop.main.run()

GCD - DispatchWorkItem

import Foundation

let task1 = DispatchWorkItem(qos: .utility) {
    print("1 시작")
    sleep(3)
    print("1 완료")
}

let task2 = DispatchWorkItem {
    print("2 시작")
    print("2 완료")
}

let queue = DispatchQueue(label: "com.알쏭달쏭.serial")

queue.async(execute: task1)
queue.async(execute: task2)

sleep(4)
task2.cancel()

RunLoop.main.run()
Clone this wiki locally