【发布时间】:2020-11-14 14:23:50
【问题描述】:
我有一个文本框,可以防止用户编写我用正则表达式指定的不允许的字符,如果用户写了其中任何一个,就会出现一个弹出窗口并在那里停留 5 秒钟,我使用这个持续时间Task.Delay(5000, cts.Token) 也有一个取消标记,如果用户写了一个允许的字符,当弹出窗口出现在屏幕上时,弹出窗口就会消失,并且延迟任务被取消和处理,但是如果我写了一个不允许的字符,然后立即写一个允许的字符,如果我做得非常快,那么当我写一个不允许的字符打开弹出窗口时,弹出窗口会在不到 5 秒内消失(随机秒,我认为这是因为延迟任务在那一刻被取消,然后导致弹出窗口消失),这与我没有使用取消令牌取消延迟任务时的问题相同。但是使用我编写的代码,我不知道任务是如何没有完全取消的,或者可能确实取消了,但问题出在其他问题上......
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);
}
}
【问题讨论】:
标签: c# wpf task cancellation-token