How to add SCNNodes without blocking main thread?
<p>I'm creating and adding a large number of SCNNodes to a SceneKit scene, which causes the app to freeze for a second or two.</p>

<p>I thought I could fix this by putting all the action in a background thread using <code>DispatchQueue.global(qos: .background).async()</code>, but no dice. It behaves exactly the same.</p>

<p>I saw <a href="https://stackoverflow.com/a/29758556/149097">this answer</a> and put the nodes through <a href="https://developer.apple.com/reference/scenekit/scnscenerenderer/1522798-prepare" rel="noreferrer"><code>SCNView.prepare()</code></a> before adding them, hoping it would slow down the background thread and prevent blocking. It didn't.</p>

<p>Here's a test function that reproduces the problem:</p>

<pre><code>func spawnNodesInBackground() {
    // put all the action in a background thread
    DispatchQueue.global(qos: .background).async {
        var nodes = [SCNNode]()
        for i in 0...5000 {
            // create a simple SCNNode
            let node = SCNNode()
            node.position = SCNVector3(i, i, i)
            let geometry = SCNSphere(radius: 1)
            geometry.firstMaterial?.diffuse.contents = UIColor.white.cgColor
            node.geometry = geometry
            nodes.append(node)
        }
        // run the nodes through prepare()
        self.mySCNView.prepare(nodes, completionHandler: { (Bool) in
            // nodes are prepared, add them to scene
            for node in nodes {
                self.myRootNode.addChildNode(node)
            }
        })
    }
}
</code></pre>

<p>When I call <code>spawnNodesInBackground()</code> I expect the scene to continue rendering normally (perhaps at a reduced frame rate) while new nodes are added at whatever pace the CPU is comfortable with. Instead the app freezes completely for a second or two, then all the new nodes appear at once.</p>

<p>Why is this happening, and how can I add a large number of nodes without blocking the main thread?</p>