---
title: "setCancelHandler(handler:)"
framework: dispatch
role: symbol
role_heading: Instance Method
path: "dispatch/dispatchsourceprotocol/setcancelhandler(handler:)"
---

# setCancelHandler(handler:)

Sets the cancellation handler block for the dispatch source.

## Declaration

```swift
func setCancelHandler(handler: DispatchWorkItem)
```

## Parameters

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

## Discussion

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() 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.

## See Also

### Canceling a Dispatch Source

- [cancel()](dispatch/dispatchsourceprotocol/cancel().md)
- [isCancelled](dispatch/dispatchsourceprotocol/iscancelled.md)
- [setCancelHandler(qos:flags:handler:)](dispatch/dispatchsourceprotocol/setcancelhandler(qos:flags:handler:).md)
