Skip to content

Instantly share code, notes, and snippets.

@akkyie
Created June 30, 2022 07:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akkyie/7115da5d89b3cff1aad71ff93b25efd5 to your computer and use it in GitHub Desktop.
Save akkyie/7115da5d89b3cff1aad71ff93b25efd5 to your computer and use it in GitHub Desktop.
import Cocoa
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
class A { // Taskでselfを使わないパターン
var task: Task<Void, Error>?
init() {
print("init")
}
func start() {
print("start")
task = Task {
try await Task.sleep(nanoseconds: NSEC_PER_SEC)
print("done without self")
}
}
deinit {
print("deinit")
task?.cancel()
}
}
autoreleasepool {
let a = A()
a.start()
print(a)
}
// init
// start
// __lldb_expr_91.A
// deinit
Thread.sleep(forTimeInterval: 1)
print("====================")
class B { // Taskで最後までselfを使うパターン
var task: Task<Void, Error>?
init() {
print("init")
}
func start() {
print("start")
task = Task {
try await Task.sleep(nanoseconds: NSEC_PER_SEC / 2)
print("done with self: \(self)")
}
}
deinit {
print("deinit")
task?.cancel()
}
}
autoreleasepool {
let b = B()
b.start()
print(b)
}
// init
// start
// __lldb_expr_91.B
// done with self: __lldb_expr_91.B
// deinit
Thread.sleep(forTimeInterval: 1)
print("====================")
class C { // 外側で弱参照するパターン
var task: Task<Void, Error>?
init() {
print("init")
}
func start() {
print("start before")
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
print("start after: \(self)")
self?.task = Task {
try await Task.sleep(nanoseconds: NSEC_PER_SEC)
print("done with self: \(self)")
}
}
}
deinit {
print("deinit")
task?.cancel()
}
}
autoreleasepool {
let c = C()
c.start()
// startのasyncAfterまで残るように1秒持つ
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
print(c)
}
}
// init
// start before
// start after: Optional(__lldb_expr_91.C)
// __lldb_expr_91.C
// deinit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment