40

I am currently playing around with Grand Central Dispatch and discovered a class called DispatchWorkItem. The documentation seems a little incomplete so I am not sure about using it the right way. I created the following snippet and expected something different. I expected that the item will be cancelled after calling cancel on it. But the iteration continues for some reason. Any ideas what I am doing wrong? The code seems fine for me.

@IBAction func testDispatchItems() {
    let queue = DispatchQueue.global(attributes:.qosUserInitiated)
    let item = DispatchWorkItem { [weak self] in
        for i in 0...10000000 {
            print(i)
            self?.heavyWork()
        }
    }

    queue.async(execute: item)
    queue.after(walltime: .now() + 2) {
        item.cancel()
    }
}

3 Answers 3

76

GCD does not perform preemptive cancelations. So, to stop a work item that has already started, you have to test for cancelations yourself. In Swift, cancel the DispatchWorkItem. In Objective-C, call dispatch_block_cancel on the block you created with dispatch_block_create. You can then test to see if was canceled or not with isCancelled in Swift (known as dispatch_block_testcancel in Objective-C).

func testDispatchItems() {
    let queue = DispatchQueue.global()

    var item: DispatchWorkItem?

    // create work item

    item = DispatchWorkItem { [weak self] in
        for i in 0 ... 10_000_000 {
            if item?.isCancelled ?? true { break }
            print(i)
            self?.heavyWork()
        }
        item = nil    // resolve strong reference cycle of the `DispatchWorkItem`
    }

    // start it

    queue.async(execute: item!)

    // after five seconds, stop it if it hasn't already

    queue.asyncAfter(deadline: .now() + 5) {
        item?.cancel()
        item = nil
    }
}

Or, in Objective-C:

- (void)testDispatchItem {
    dispatch_queue_t queue = dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0);

    static dispatch_block_t block = nil;  // either static or property

    __weak typeof(self) weakSelf = self;

    block = dispatch_block_create(0, ^{
        for (long i = 0; i < 10000000; i++) {
            if (dispatch_block_testcancel(block)) { break; }
            NSLog(@"%ld", i);
            [weakSelf heavyWork];
        }

        block = nil;
    });

    // start it

    dispatch_async(queue, block);

    // after five seconds, stop it if it hasn't already

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (block) { dispatch_block_cancel(block); }
    });
}
17
  • Can DispatchWorkItem be reused after cancelled?
    – pixelfreak
    Commented Oct 12, 2016 at 13:36
  • 1
    @Rob - doesn't this create a retain cycle?
    – mattsven
    Commented Mar 7, 2017 at 12:55
  • 2
    @mattsven - Good catch. You're absolutely right. Unfortunately, you can't use [weak item] or [unowned item] patterns when instantiating the DispatchWorkItem (the typical method for resolving strong reference cycles), so you have to manually nil the item at the end of the closure like I have in the revised answer. (But we can use the typical [weak item] pattern in the block where we asyncAfter the cancel.)
    – Rob
    Commented Mar 7, 2017 at 18:19
  • 1
    @Rob That was my first thought too. Unfortunately if the DispatchItem is cancelled before it is executed, the memory is leaked.
    – mattsven
    Commented Mar 7, 2017 at 21:00
  • 1
    I’ve added qualifier “of the DispatchWorkItem” to that code comment...
    – Rob
    Commented Apr 1, 2020 at 17:34
1

DispatchWorkItem without DispatchQueue

 let workItem = DispatchWorkItem{
    //write youre code here
 }
 workItem.cancel()// For Stop

DispatchWorkItem with DispatchQueue

let workItem = DispatchWorkItem{
   //write youre code here
}
DispatchQueue.main.async(execute: workItem)
workItem.cancel()// For Stop

Execute

workItem.perform()// For Execute
workItem.wait()// For Delay Execute
0

There is no asynchronous API where calling a "Cancel" method will cancel a running operation. In every single case, a "Cancel" method will do something so the operation can find out whether it is cancelled, and the operation must check this from time to time and then stop doing more work by itself.

I don't know the API in question, but typically it would be something like

        for i in 0...10000000 {
            if (self?.cancelled)
                break;

            print(i)
            self?.heavyWork()
        }
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.