Task cancellation

import UIKit
import _Concurrency

class Tester {
  
  init() {
    
  }
  
  var task: Task<Void, Never>?
  
  deinit {
    print("deinit")
  }
  
  func dosomething() {
    
    print("111")
    task = Task {
      
      print("222")

      await userTapEvent()
      
      print("333")

    }
    print("444")
    
    task?.cancel()
        
  }
  
  func userTapEvent() async {
    
    await withCheckedContinuation{ (continuation: CheckedContinuation<Void, Never>) in
            
      sleep(2)
      continuation.resume()
      
    }
    
  }
  
}


Tester().dosomething()

why in the playground I have cancelled the task. but seems the deinit function isnt called.

If this is code in a playground, top-level variables are unlikely to get deinitialized. Try that in a project.

3 Likes