<!--
{
  "availability" : [
    "iOS: 4.0.0 -",
    "iPadOS: 4.0.0 -",
    "macCatalyst: 13.1.0 -",
    "macOS: 10.6.0 -",
    "tvOS: -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Dispatch",
  "identifier" : "/documentation/Dispatch/dispatch_source_set_cancel_handler",
  "metadataVersion" : "0.1.0",
  "role" : "Function",
  "symbol" : {
    "kind" : "Function",
    "modules" : [
      "Dispatch"
    ],
    "preciseIdentifier" : "c:@F@dispatch_source_set_cancel_handler"
  },
  "title" : "dispatch_source_set_cancel_handler"
}
-->

# dispatch_source_set_cancel_handler

Sets the cancellation handler block for the given dispatch source.

```
extern void dispatch_source_set_cancel_handler(dispatch_source_t source, dispatch_block_t handler);
```

## Parameters

`source`

The dispatch source to modify. This parameter cannot be `NULL`.

`handler`

The cancellation handler block to submit to the source’s target queue. This function performs a `Block_copy` on behalf of the caller, and `Block_release` on the previous handler (if any).  This parameter can be `NULL`.

## Discussion

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

> Important:
> To safely close a file descriptor or destroy a Mach port, a cancellation handler is required for the source 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)