Search code examples
iosmultithreadingcore-datagrand-central-dispatch

Set CoreData NSManagedObjectContext thread priority


At least since iOS 9 the only non-deprecated thread concurrency type for Core Data operations, not running in the main thread, is NSPrivateQueueConcurrencyType. My problem is now, that I want to change the thread priority for that, like this:

...:(int) neededPriority {
  _queue = dispatch_queue_create("Worker", DISPATCH_QUEUE_SERIAL);
  dispatch_set_target_queue(_queue,
    dispatch_get_global_queue(neededPriority, 0));

Sometimes I need a high priority, sometimes a low. But when I call [_privateContext performBlock:...] I can't pass a parameter with the needed priority, nor has the context any property to set its thread priority.
Therefore my question: is there any way to put the context queue into a certain thread priority?


Solution

  • NSManagedObjectContext instances are assigned queues, not threads. The queue associated with the performBlock routine may be run an arbitrary background thread, so you can't assign a general priority to a context.

    Instead, from inside the performBlock block, you can call NSThread.setThreadPriority to change the priority of the thread that is handling that block.

    You might want to save the thread's priority before changing it, and reset it at the end of the block.