如何退出运行循环? [英] How to exit a runloop?

查看:90
本文介绍了如何退出运行循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有一个Swift命令行程序:

So, I have a Swift command-line program:

import Foundation

print("start")

startAsyncNetworkingStuff()

RunLoop.current.run()

print("end")

代码编译没有错误.异步网络代码运行良好,可以获取其所有数据,打印结果,并最终调用其完成功能.

The code compiles without error. The async networking code runs just fine, fetches all its data, prints the result, and eventually calls its completion function.

如何获取完成功能以超出当前的运行循环,以使最后一个结束"得到打印?

How do I get that completion function to break out of above current runloop so that the last "end" gets printed?

已添加:

将RunLoop.current.run()替换为以下内容:

Replacing RunLoop.current.run() with the following:

print("start")

var shouldKeepRunning = true

startAsyncNetworkingStuff()

let runLoop = RunLoop.current
while (   shouldKeepRunning
       && runLoop.run(mode:   .defaultRunLoopMode,
                      before: .distantFuture ) ) {
}

print("end")

设置

shouldKeepRunning = false

异步网络完成功能中的

仍然不会导致打印"end". (这是通过将shouldKeepRunning = false语句与实际打印到控制台的print语句括起来进行检查的).缺少什么?

in the async network completion function still does not result in "end" getting printed. (This was checked by bracketing the shouldKeepRunning = false statement with print statements which actually do print to console). What is missing?

推荐答案

对于命令行界面,请使用此模式,并将完成处理程序添加到您的 AsyncNetworkingStuff 中(感谢Rob进行了代码改进):

For a command line interface use this pattern and add a completion handler to your AsyncNetworkingStuff (thanks to Rob for code improvement):

print("start")

let runLoop = CFRunLoopGetCurrent()
startAsyncNetworkingStuff() { result in 
   CFRunLoopStop(runLoop)
}

CFRunLoopRun()
print("end")
exit(EXIT_SUCCESS)

请不要使用难看的while循环.

Please don't use ugly while loops.

这篇关于如何退出运行循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆