【问题标题】:Proper way to end an Async process结束异步进程的正确方法
【发布时间】:2018-03-10 22:51:27
【问题描述】:

所以我有这个代码:

@IBAction func onStart(_ sender: Any) {
    DispatchQueue(label: "SyncQueue").async{
        for i in 0..<numberOfItemToDownload {
            // download data from the internet this may takes longer depends on the connection speed and data being download
            if isCancelled {
                DispatchQueue.main.async { // dismiss the progress ViewController (displayed modally) }
                break
            }
        }
    }
}

@IBAction func onEnd(_ sender: Any) {
        isCancelled = true
}

这可以正常工作,但是如果当前正在下载的项目需要更长的时间,那么用户点击“结束”按钮,“进度对话框”在当前项目完成之前不会关闭。这使得“结束”按钮在用户看来不起作用。

在 Android 中,我们可以中断 AsyncTask 进程并结束它。在 Swift 中还有另一种方法吗?就像当用户点击“结束”时,该过程应该立即停止并关闭“进度对话框”。

【问题讨论】:

标签: ios swift swift4 dispatch-queue


【解决方案1】:

GDC 不容易取消。

使用NSOperation 子类,您可以轻松快速地取消。

【讨论】:

  • 在旧版本中是正确的,但从 swift 3 开始,可以使用 Dispatch Work item 取消块执行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-30
  • 1970-01-01
  • 1970-01-01
  • 2016-09-29
相关资源
最近更新 更多