multithreading - 操作系统 : Creating a thread in a screensaver

标签 multithreading swift macos screensaver

我正在为 OSX 创建一个简单的屏幕保护程序,并想为一些后台计算创建一个线程。

我在 SO 中找到了这个函数,它将在 X 秒后创建一个线程:

func backgroundThread(delay: Double = 0.0, background: (() -> Void)? = nil, completion: (() -> Void)? = nil) {
    dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.rawValue), 0)) {
        if(background != nil){ background!(); }

        let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
        dispatch_after(popTime, dispatch_get_main_queue()) {
            if(completion != nil){ completion!(); }
        }
    }
}

但是当我将它添加到 init 时它似乎不起作用:

override init?(frame: NSRect, isPreview: Bool) {
    super.init(frame: frame, isPreview: isPreview);
    let fontSize: CGFloat = 20;
    let frameHeight: CGFloat = self.frame.size.height;
    let font = NSFont(name: "Times New Roman", size: fontSize);
    let paragraph = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle;
    paragraph.alignment = NSTextAlignment.Center;
    let textColor = NSColor(calibratedRed: 255.0, green: 255.0, blue: 255.0, alpha: 1.0);

    self.backgroundThread(3.0, background: {

        let w:String = "test";
        let textRect: NSRect = NSMakeRect(1, (frameHeight-CGFloat(fontSize*CGFloat(1))-30), 80, 30);
        if let actualFont = font {
            let textFontAttributes = [
                NSFontAttributeName: actualFont,
                NSForegroundColorAttributeName: textColor,
                NSParagraphStyleAttributeName: paragraph
            ];

            w.drawInRect(NSOffsetRect(textRect, 0, 1), withAttributes: textFontAttributes);
        }
    });
}

它应该在 3 秒后在不同的线程中显示该字符串,但事实并非如此。我错过了什么?

最佳答案

GUI线程必须是主线程,不能是后台线程

所以使用完成闭包

self.backgroundThread(3.0, completion: {

或者只使用必要的代码

dispatch_after(3.0, dispatch_get_main_queue()) {
    ...
}

或者使用像Eki这样的框架

关于multithreading - 操作系统 : Creating a thread in a screensaver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35137604/

相关文章:

c# - 调用相同对象的多个线程同时运行。它会引起问题吗?

c++ - boost::asio 中的 post 和 dispatch 有什么区别?

c# - ThreadStatic、ThreadLocal、GetData 比为线程创建对象实例有什么优势?

ios - Swift 按钮按下复制文本

xcode - OS X 应用程序在 XCode 外部启动时运行缓慢

java - 在多个线程中调用多个rest/soap服务并等待它们的响应

Swift : Parse, 基于nsdate()查询日期字段

ios - 当用户想要在从一个选项卡导航到另一个选项卡时不自动刷新时如何刷新 webViewController

python - 使用 venv 时环境 $PATH 不同

python - 在 mac 上更改 python 路径?