[swift-corelibs-dev] New GCD API change: DispatchWorkItems should be retained by their groups

Karl razielim at gmail.com
Thu Jul 7 12:01:15 CDT 2016


Hi,

I’d like to propose a change to the new GCD API; that DispatchWorkItems be retained by their groups (and in turn, for them to be retained by their queues). This allows for whoever created the work item to create a weak reference to it, as an indicator for whether or not it has finished executing.

For example, let’s say I have some kind of class which manages a library of files. I want to have a refresh operation which runs on a background queue, enumerating the documents and perhaps even opening them and extracting some metadata:

class DocumentLibrary {

    weak var refreshOperation : DispatchWorkItem?

    func refresh(force:Bool = false) {

        If let ongoingOperation = refreshOperation {
	    if force == true {
                ongoingOperation.cancel()  // force an update
            }
            else {
                return  // already refreshing
            }
        }

        refreshOperation = DispatchWorkItem(….)  // processes the files, returns the results on the main queue
        DispatchQueue.global().async(refreshOperation)
    }
}

This relies on the fact that weak references are thread-safe, and avoids the need for an explicit completion handler which nils the variable.

Thoughts?

Karl


More information about the swift-corelibs-dev mailing list