How to stop a DispatchWorkItem in GCD?
<p>I am currently playing around with <strong>Grand Central Dispatch</strong> and discovered a class called <code>DispatchWorkItem</code>. 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 <code>cancel</code> on it. But the iteration continues for some reason. Any ideas what I am doing wrong? The code seems fine for me.  </p>

<pre><code>@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()
    }
}
</code></pre>