<!--
{
  "availability" : [
    "iOS: -",
    "iPadOS: -",
    "macCatalyst: -",
    "macOS: -",
    "tvOS: -",
    "visionOS: -",
    "watchOS: -"
  ],
  "documentType" : "symbol",
  "framework" : "Dispatch",
  "identifier" : "/documentation/Dispatch/DispatchSourceProtocol/setCancelHandler(qos:flags:handler:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Dispatch"
    ],
    "preciseIdentifier" : "s:So18OS_dispatch_sourceP8DispatchE16setCancelHandler3qos5flags7handleryAC0D3QoSV_AC0D13WorkItemFlagsVyyXLSgtF"
  },
  "title" : "setCancelHandler(qos:flags:handler:)"
}
-->

# setCancelHandler(qos:flags:handler:)

Sets the cancellation handler block for the dispatch source with the specified quality-of-service class and work item options.

```
func setCancelHandler(qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], handler: Self.DispatchSourceHandler?)
```

## Parameters

`qos`

The quality-of-service to apply to the handler block.

`flags`

Configuration flags for the work item. For a list of possible values, see [`DispatchWorkItemFlags`](/documentation/Dispatch/DispatchWorkItemFlags).

`handler`

The event handler block to submit to the source’s target queue.

## Discussion

The cancellation handler (if specified) is submitted to the source’s target queue in response to a call to a call to the [`cancel()`](/documentation/Dispatch/DispatchSourceProtocol/cancel()) method once the system has released all references to the source’s underlying handle and the source’s event handler block has returned.

To safely close a file descriptor or destroy a Mach port, a cancellation handler is required for that descriptor or port. Closing the descriptor or port before the cancellation handler runs can result in a race condition. If a new descriptor is allocated with the same value as the recently closed descriptor while the source’s event handler is still running, the event handler may read/write data using the wrong descriptor.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)