【问题标题】:Forcing a timeout for FileManager().copyItem(_:_)强制 FileManager().copyItem(_:_) 超时
【发布时间】:2021-05-13 11:02:09
【问题描述】:

我正在使用

try FileManager.default.copyItem(at: inFile, to: outFile)

问题在于它是一个存在问题的网络上的大文件,并且由无人看管的人完成处理。我希望能够告诉 FileManager 只需花一分钟的时间来完成复制,否则就不行了。

我好像在文档中找不到,今天我的兵符很弱。

【问题讨论】:

  • 也许有这些要求,您应该编写自己的文件副本,部分完成,然后您可以拥有更多控制权,例如早点退出。

标签: objective-c swift macos timeout nsfilemanager


【解决方案1】:

我最终使用 dispatchWorkItem 和自定义错误结构扩展了 FileManager。

public extension FileManager {
    struct TimeoutError:Error{
        let source:URL
        let destination:URL
        let timeOut:Double
    }

    func timedOutCopy(at source:URL, to destionation:URL, timeOut:Double = 15.0) throws {
        var cpError:Error?
        let d = DispatchWorkItem(block: {
            do {
                try self.copyItem(at: source, to: destionation)
            } catch {
                cpError = error
            }
        })
        DispatchQueue.global().async(execute: d)
        if d.wait(wallTimeout: DispatchWallTime.now() + timeOut) != .success {
            d.cancel()
            throw TimeoutError(source: source, destination: destionation, timeOut: timeOut)
        } else {
            if let cpError = cpError {throw cpError}
        }
    }
}

【讨论】:

    猜你喜欢
    • 2011-09-22
    • 1970-01-01
    • 2015-04-20
    • 2018-08-18
    • 2011-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多