我尝试在Swift Playground中测试取消DispatchWork
项目,虽然在执行的前几毫秒内出现了错误,我不确定它实际上指示了什么,我也无法判断错误是否导致取消而不是cancel()
方法......
func testDispatchWorkItems() {
let queue = DispatchQueue.global(qos: .userInitiated)
var item: DispatchWorkItem?
// create work item
item = DispatchWorkItem {
for i in 0 ... 100000 {
if item!.isCancelled { break }
print(i)
}
}
// start it
queue.async(execute: item!)
// after three seconds, stop it
queue.asyncAfter(deadline: .now() + 3) {
item?.cancel()
}
}
testDispatchWorkItems()
2016-10-26 11:14:33.898 com.apple.dt.Xcode.PlaygroundStub-macosx[30685:18567692] Error encountered communicating with Xcode: Error Domain=DVTPlaygroundCommunicationErrorDomain Code=1 "Cannot send data because stream is closed." UserInfo={NSLocalizedDescription=Cannot send data because stream is closed.}
有人知道这个错误表明了什么吗?
答案 0 :(得分:9)
将needsIndefiniteExecution
设置为true
可以省略此警告。一旦操场执行比线程处理更早结束,就会发出警告。
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true