From c12b9ae8792c2aaa06f005843427acd34bab18fa Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Fri, 9 Sep 2022 23:51:41 -0400 Subject: [PATCH] Parent background context to PSC to prevent hangs when updating widget --- Persistence/Sources/Persistence/PersistentContainer.swift | 5 +++-- Reader/Widgets/WidgetHelper.swift | 3 +++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/Persistence/Sources/Persistence/PersistentContainer.swift b/Persistence/Sources/Persistence/PersistentContainer.swift index e632508..615fe1a 100644 --- a/Persistence/Sources/Persistence/PersistentContainer.swift +++ b/Persistence/Sources/Persistence/PersistentContainer.swift @@ -19,8 +19,9 @@ public class PersistentContainer: NSPersistentContainer, @unchecked Sendable { public private(set) lazy var backgroundContext: NSManagedObjectContext = { let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) - // todo: should the background context really be parented to the view context, or should they both be direct children of the PSC? - context.parent = self.viewContext + // the background context needs to be parented directly to the PSC + // if it's parented to the viewContext, it blocks the viewContext (and potentially the main thread) when it needs to look things up + context.persistentStoreCoordinator = self.persistentStoreCoordinator return context }() diff --git a/Reader/Widgets/WidgetHelper.swift b/Reader/Widgets/WidgetHelper.swift index 1ffb686..ed282cc 100644 --- a/Reader/Widgets/WidgetHelper.swift +++ b/Reader/Widgets/WidgetHelper.swift @@ -11,6 +11,7 @@ import Persistence import OSLog private let logger = Logger(subsystem: "net.shadowfacts.Reader", category: "WidgetHelper") +private let signposter = OSSignposter(logger: logger) struct WidgetHelper { private init() {} @@ -26,7 +27,9 @@ struct WidgetHelper { req.sortDescriptors = [NSSortDescriptor(key: "published", ascending: false)] req.fetchLimit = 32 req.predicate = NSPredicate(format: "read = NO") + let state = signposter.beginInterval("fetch") var items = (try? context.fetch(req)) ?? [] + signposter.endInterval("fetch", state) var prioritizedItems: [Item] = []