I have a textbox that prevents the user from writing the unallowed characters that I've specified with regex, and if the user writes any of them, a popup shows up and stays there for 5 seconds, and I made this duration using the Task.Delay(5000, cts.Token)
which has a cancellation token as well, and while the popup is on the screen if the user writes an allowed character, then the popup disappears, and that delay task gets canceled and disposed, but if I write an unallowed char, and then immediately write an allowed char, and if I do it really fast, then when I write an unallowed char to open the popup, the popup disappears in less than 5 seconds (in a random second, that I think it's because the delay task gets canceled at that moment and then causes the popup to disappear), which is the same problem as when I didn't use the cancellation tokens to cancel the delay task. But with the codes that I've written, I don't know how the task doesn't get canceled completely, or maybe it does but the problem is something else ...
CancellationTokenSource cts;
protected async override void OnPreviewTextInput(TextCompositionEventArgs e)
{
if (txtName.IsFocused)
{
if (cts != null && !regex.IsMatch(e.Text))
{
cts.Cancel();
cts.Dispose();
}
cts = new CancellationTokenSource();
if (regex.IsMatch(e.Text))
{
e.Handled = true;
txtName.CaretIndex = txtName.Text.Length;
if (AlertPopup.IsOpen == false)
{
AlertPopup.IsOpen = true;
txtName.Focus();
try
{
await Task.Delay(5000, cts.Token);
}
catch (TaskCanceledException) { }
finally
{
AlertPopup.IsOpen = false;
}
}
}
else
{
AlertPopup.IsOpen = false;
}
base.OnPreviewTextInput(e);
}
}