I was reading Stephen Cleary's blog post about cancellation, and I saw something I haven't seen before in the following code snippet.
Constructor() => CancelButton.Enabled = false;
private CancellationTokenSource? _cts;
async void StartButton_Click(..)
{
StartButton.Enabled = false;
CancelButton.Enabled = true;
// Create a CTS for manual cancellation requests.
using var cts = _cts = new();
try
{
// Pass the token for that CTS to lower-level code.
await DoSomethingAsync(_cts.Token);
.. // Display success in UI.
}
catch (Exception ex)
{
.. // Display error in UI.
}
finally
{
StartButton.Enabled = true;
CancelButton.Enabled = false;
}
}
async void CancelButton_Click(..)
{
// Manually cancel the CTS.
_cts!.Cancel();
}
Particularly, the using var cts = _cts = new(); line.
Is the using managing the disposal of the private member as well as the local variable?
Why assign the local variable if it's not used anywhere?
What is going on here?