简体   繁体   English

CADisplayLink 回调是否始终在主线程上运行?

[英]Is CADisplayLink callback always runs on the main thread?

I couldn't find any direct answer online nor within the docs about this.我在网上和文档中都找不到任何直接的答案。 If I'm setting up CADisplayLink with the following:如果我使用以下内容设置CADisplayLink

 let displayLink = CADisplayLink(target: self, selector: #selector(updateShimmer))
 displayLink.add(to: .current, forMode: .common)

@objc func updateShimmer() {
   print(Thread.isMainThread)
}

I'm getting true.我说实话了。 I know that I can wrap this within a DispatchQueue.main but I was wondering, is it always dispatched on the main queue?我知道我可以将它包装在DispatchQueue.main但我想知道,它是否总是在主队列上调度? Or should I wrap it anyway?还是我应该把它包起来?

You do not need to manually dispatch code inside your display link handler to the main thread.您不需要将显示链接处理程序中的代码手动分派到主线程。 Timers and display links added to a particular run loop will always run on the thread associated with that run loop.添加到特定运行循环的计时器和显示链接将始终在与该运行循环关联的线程上运行。 For more information, see Threading Programming Guide: Run Loops .有关更多信息,请参阅线程编程指南:运行循环

Bottom line, if you add(to:forMode:) to the main run loop, the main run loop always runs on the main thread.最重要的是,如果您add(to:forMode:)主运行循环中,则主运行循环始终在主线程上运行。

That having been said, if you want to make sure it always runs on the main thread, I would suggest being explicit and adding it to .main , not just .current .话虽如此,如果您想确保它始终在主线程上运行,我建议明确并将其添加到.main ,而不仅仅是.current That removes any ambiguity:这消除了任何歧义:

let displayLink = CADisplayLink(target: self, selector: #selector(updateShimmer(_:)))
displayLink.add(to: .main, forMode: .common)

Note, I also tweaked the signature of updateShimmer to accept a parameter.请注意,我还调整了updateShimmer的签名以接受参数。 The display link will be passed to it.显示链接将传递给它。 It's often useful to have that reference inside the method.在方法中包含该引用通常很有用。 And, regardless, it makes one's code more self-evident: You can just glance at this method now and understand that this is a display link handler:而且,无论如何,它使一个人的代码更加不言而喻:您现在只需看一眼这个方法就会明白这是一个显示链接处理程序:

@objc func updateShimmer(_ displayLink: CADisplayLink) {
     ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM