Truyền CancellationToken vào các async methods và kiểm tra token.IsCancellationRequested định kỳ.
- Ném
OperationCanceledExceptionkhi phát hiện cancellation. - Gọi
cts.Cancel()để báo hiệu hủy bỏ; dùngcts.CancelAfter(TimeSpan)cho timeout tự động. - Xử lý cancellation đúng cách ngăn resource leak và orphaned tasks.
Pass a CancellationToken to async methods and periodically check token.IsCancellationRequested.
- Throw
OperationCanceledExceptionwhen cancellation is detected. - Call
cts.Cancel()to signal cancellation; usects.CancelAfter(TimeSpan)for automatic timeout. - Properly handling cancellation prevents resource leaks and orphaned tasks.