我正在使用GCD函数解析一个非常大的CSV文件(请参见下面的代码)。
如果遇到错误,我想取消dispatch_io_read
。有没有办法做到这一点?
dispatch_io_read(channel,
0,
Int.max,
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0))
{ (done, data, error) in
guard error == 0 else {
print("Read Error: \(error)")
return
}
if done {
lineBuffer.dealloc(bufferSize)
}
dispatch_data_apply(data)
{ (region, offset, buffer, size) -> Bool in
print(size)
let bytes = UnsafePointer<UInt8>(buffer)
for var i = 0; i < size; i++ {
switch bytes[i] {
case self.cr: // ignore \r
break
case self.lf: // newline
lineBuffer[bufferLength] = 0x00 // Null terminated
line(line: String(UTF8String: lineBuffer)!)
bufferLength = 0
case _ where bufferLength < (bufferSize - 1): // Leave space for null termination
lineBuffer[bufferLength++] = CChar(bytes[i])
default:
return false // Overflow! I would like to stop reading the file here.
}
}
return true
}
}
最佳答案
调用dispatch_io_close(DISPATCH_IO_STOP)
将导致正在运行的dispatch_io_read
操作被中断,并且其处理程序将传递给ECANCELED
错误(以及部分结果),请参见dispatch_io_close(3)
联机帮助页。
请注意,这不会中断实际的I / O系统调用,它只是防止输入其他I / O系统调用,因此您可能必须设置I / O通道高水位标记以确保适当的I / O粒度级别。为您的应用程序。
关于objective-c - 取消dispatch_io_read,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30804903/