CancellationTokenRegistration disposal.
should i dispose CancellationTokenRegistration for global shared CancellationTokenSource's token (eg: that token only exists while application is running)?
Scenario:
Simple console app that listen for TCP connections recv/send data.
Context:
Server.StartListen(token)
token is global cancellation token source's token. For each new connection accepted, its forward token too for these methods (don't need to allocate own token source because it will not be used elsewhere).
Once accepted, new connection is created and server call Connection.StartAsync(token)
will forward too the token, its a blocking task that will complete both read/write tasks complete (or fail but exceptions proper logged).
But if server cancel token source early, the token registration will call Connection.Disconnect()
that send a disconnect packet to client.
Should i dispose token registration or not? What happen if i do not dispose the registration?
2 Replies
there could be resources allocated when you make a registration, so as a general rule yes when its use is finished it should be disposed
If you don't dispose the token registration, then when the token is cancelled, even long after that
StartAsync
method has returned, the callback will still be called. If you call StartAsync
multiple times (and register multiple callbacks), all of them will be called when the token is cancelled
Now, if your StartAsync
is only called once, and that WhenAll
only returns on program shutdown, then the scope for damage is minimal (there's just a race where the read/write tasks complete, and the afterwards the token is cancelled)
But, not disposing a registration is a huge red flag. If I saw code which didn't dispose one it would immediately stand out as a massive problem, and I'd raise it as a bug. Disposing it is such a trivial and obviously correct thing to do, so just do it.