1

I'm working on some code that uses fire and forget tasks, which can also be cancelled.

I always thought you had to Cancel AND dispose of CancellationTokenSources, but reading here https://blog.stephencleary.com/2022/03/cancellation-2-requesting-cancellation.html, they suggest you only need to do one or the other? As Cancel() will also dispose of the timer and any registrations.

So in the case of a fire and forget task, is it OK to just call Cancel()? And not have to worry about trying to call dispose after the task completes?

wforl
  • 91
  • 9
  • The [documentation](https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtokensource#remarks) states explicitly that *"This type implements the `IDisposable` interface. When you have finished using an instance of the type, you should dispose of it either directly or indirectly."* So if we (hypothetically) say to you that it's OK to omit the `Dispose`, who are you going to believe? Us or Microsoft? – Theodor Zoulias Jun 29 '23 at 22:52
  • The link I gave is from a Microsoft MVP. Hence my confusion.... – wforl Jun 29 '23 at 22:56
  • I understand your confusion, but I don't think that it's possible to leave the `CancellationTokenSource` undisposed, and not feel dirty about it. So if it's possible to dispose it, just do it. If it's not, in other words if coding dirty is your only option, then at least you know that it's probably not the end of the world. – Theodor Zoulias Jun 29 '23 at 23:29
  • https://github.com/dotnet/runtime/issues/29970#issuecomment-504454757 seems it's not guaranteed, but that's the current implementation, as long as you don't use `CreateLinkedTokenSource` – Charlieface Jun 29 '23 at 23:32

0 Answers0