C# Windows UWP project
I have implemented CancellationTokenSource and CancellationToken in an async method that calls another method. This method contains a while loop which maintains the value of a bool variable as true until the token source is cancelled.
The async method is triggered by a mouse left button pressed event and is cancelled by a mouse left button released event occurring while using a ColorPicker control. The bool variable allows the color values to be sent to a device when true and prevents it when false.
By maintaining the value as true, the device receives varying color values continuously while the pointer is moved around the color picker as long as the mouse button remains down. Once the mouse button is released, the resulting false value (which gets set by the routine that sends the color values to the device) prevents further color messages from being sent to the device.
My code does what I want it too, but I’m concerned about potential side effects that could result if I have not implemented it correctly. I have seen at least one posting on this forum that indicates that the sequence: cancel, dispose and set to null can be used for the CancellationTokenSource. But it concerns me that I have a potentially endless while loop that depends entirely on receiving the cancellation token. So my question is whether disposing of a CancellationTokenSource too soon could prevent token.IsCanellationRequested from being set to true, and if so will adding a delay add any benefit?
The following are the related snippets from my code:
Global variables:
public static bool colorPickerPtrPressed = false;
static CancellationTokenSource cts = null;
static CancellationToken token;
Mouse button events:
private void ColorPicker_PtrPressedEvent(object sender, PointerRoutedEventArgs e)
{
if(cts == null) cts = new CancellationTokenSource();
token = cts.Token;
var picker = sender as ColorPicker.ColorPicker;
colorPickerPtrPressed = true;
(picker.DataContext as SpheroViewModel).Color = picker.SelectedColor.Color;
ColorChange(token);
}
private void ColorPicker_PtrReleasedEvent(object sender, PointerRoutedEventArgs e)
{
if (cts != null)
{
cts.Cancel();
Task.Delay(500).Wait(); // Allow some time for cancel to take effect
cts.Dispose();
cts = null;
}
}
Cancellation token methods:
public static async Task ColorChange(CancellationToken token)
{
await Task.Run(() =>
AllowColorChange(token), token);
}
public static void AllowColorChange(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
colorPickerPtrPressed = true; // Maintain value as true
Task.Delay(100).Wait(); // allow color updates periodically
}
return;
}