在OperationQueue中打印1到10不打印整数

哈宁亚

我正在研究Combine Scheduler,我从Raywenderlich的书中获得了示例代码

let queue = OperationQueue()

let subscription = (1...10).publisher
  .receive(on: queue)
  .sink { value in
    print("Received \(value) on thread \(Thread.current.number)")
  }

这本书解释了OperationQueue使用所有可用线程,因此打印顺序和线程可能是随机的。我理解这部分,但是当我在操场上运行此代码时,我只看到10个数字中的5个。

Received 1 on thread 7
Received 2 on thread 6
Received 3 on thread 5
Received 7 on thread 9
Received 6 on thread 4

为什么该代码不能显示全部10个数字?

查尔斯·玛丽亚

您需要导入PlaygroundSupportPlaygroundPage.current.needsIndefiniteExecution = true在文件顶部设置

如果您使用另一个接收器方法,也将获得一个完成处理程序块的接收器方法,则在该完成处理程序中,您应调用 PlaygroundPage.current.finishExecution()

编辑:调用PlaygroundPage.current.finishExecution()队列上的障碍块,否则在您的打印语句全部执行之前被调用。

这是我的测试代码:

PlaygroundPage.current.needsIndefiniteExecution = true

let queue = OperationQueue()

let subscription = (1...10).publisher
    .receive(on: queue)
    .sink(receiveCompletion: { _ in
        queue.addBarrierBlock {
            print("Finished")
            PlaygroundPage.current.finishExecution()
        }
    }, receiveValue: { value in
        print("Received \(value) on thread \(Thread.current)")
    })

并输出:

Received 1 on thread <NSThread: 0x7fd86f204080>{number = 2, name = (null)}
Received 2 on thread <NSThread: 0x7fd86f404340>{number = 3, name = (null)}
Received 3 on thread <NSThread: 0x7fd86f404430>{number = 4, name = (null)}
Received 7 on thread <NSThread: 0x7fd86f405240>{number = 5, name = (null)}
Received 6 on thread <NSThread: 0x7fd86f205c50>{number = 6, name = (null)}
Received 10 on thread <NSThread: 0x7fd86ce487f0>{number = 7, name = (null)}
Received 5 on thread <NSThread: 0x7fd86cf048a0>{number = 10, name = (null)}
Received 9 on thread <NSThread: 0x7fd86ce49b20>{number = 11, name = (null)}
Received 4 on thread <NSThread: 0x7fd86cf2a4c0>{number = 12, name = (null)}
Received 8 on thread <NSThread: 0x7fd86ce4ad60>{number = 13, name = (null)}
Finished

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

整数值不打印?

来自分类Dev

打印从1到10的整数,只有5版面中的特定的顺序

来自分类Dev

Java不打印整数变量

来自分类Dev

为什么不打印任何整数?

来自分类Dev

为什么不打印任何整数?

来自分类Dev

为什么“A=10 echo $A”不打印 10?

来自分类Dev

打印变量不打印 /-

来自分类Dev

如何每秒打印1到10个?

来自分类Dev

在模式1和模式2之间的文件中打印数据,而不打印模式2

来自分类Dev

读取数字,然后将1到数字之间的整数打印到文件中

来自分类Dev

在Firefox中打印代码,但在IE中不打印

来自分类Dev

循环打印1至50号不打印10和20和30以及40和50

来自分类Dev

如何在Haskell中什么也不打印

来自分类Dev

如何在Julia中不打印类型?

来自分类Dev

在python中显示unicode而不打印

来自分类Dev

刀片视图不打印阵列中的数据

来自分类Dev

我在 C 中的函数不打印值

来自分类Dev

Exiftool 不打印到 ProcessBuilder 中的文件?

来自分类Dev

函数调用中的打印语句不打印值 Python

来自分类Dev

如何解决循环不打印结果并解决“在160张纸钞中,每10到50几张,总计1760美元”?

来自分类Dev

合并.sink打印不打印

来自分类Dev

打印机不打印

来自分类Dev

为什么此C代码不打印负整数?

来自分类Dev

如何在java中以相反的顺序从10到1打印计数?

来自分类Dev

QMake消息不打印

来自分类Dev

CountVectorizer不打印词汇

来自分类Dev

beautifulsoup不打印链接

来自分类Dev

类对象不打印

来自分类Dev

无效部分不打印