取消dispatch_io_read

时间:2015-06-12 13:58:19

标签: objective-c swift cocoa libdispatch

我正在使用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 
                }
        }

1 个答案:

答案 0 :(得分:1)

调用dispatch_io_close(DISPATCH_IO_STOP)会导致正在运行dispatch_io_read次操作并将其处理程序传递给ECANCELED错误(以及部分结果),请参阅dispatch_io_close(3)联机帮助页。

请注意,这不会中断实际的I / O系统调用,它只会阻止输入额外的I / O系统调用,因此您可能必须设置I / O通道高水位以确保I的适当级别/ O粒度适用于您的应用程序。