gpt4 book ai didi

c# - 如何在 C# 中创建可重新触发的延迟?

转载 作者:太空狗 更新时间:2023-10-30 01:12:37 25 4
gpt4 key购买 nike

我拥有的是用户名的字符串属性,通过 MVVM 连接到文本条目,每当设置它时,我都会调用一个方法来检查服务器以查看用户名是否可用。现在我不希望每次键入一个键时都调用它,我想要的是让它检测用户何时停止键入。

目前这是我的代码...

private string _username;
public string Username
{
get => _username;
set
{
SetProperty(ref _username, value);
Task.Run(async () => await CheckUsernameExists(1000));
}
}

然后是 CheckUsernameExists() 方法...

/// <summary>
/// Checks if the username already exists
/// </summary>
/// <returns></returns>
public async Task CheckUsernameExists(int timeoutInMilliseconds)
{
await Task.Delay(timeoutInMilliseconds);

try
{...

但是这不会重新触发它,它只是将调用延迟 1 秒。

我从 Unreal Engine 4 得到了可重触发延迟的想法 https://docs.unrealengine.com/en-US/BlueprintAPI/Utilities/FlowControl/RetriggerableDelay/index.html

UE4 发生的情况是,该函数被调用一次。然后它在可重触发延迟上启动计时器。如果在该计时器运行时再次调用该函数,它将重新启动计时器。然后,只有当它完成时,它才会调用它之​​后的代码。

有人知道如何在 C# 中执行此操作吗?谢谢!

最佳答案

standard way这样做是使用 CancellationTokenSource 对象。每次属性更改时创建一个新的,在取消前一个之后。

private string _username;
public string Username
{
get => _username;
set
{
SetProperty(ref _username, value);
CheckUsernameExistsAsync(value, 1000);
}
}

private CancellationTokenSource _cts;

private async void CheckUsernameExistsAsync(string username, int timeout)
{
try
{
_cts?.Cancel();
_cts = new CancellationTokenSource();
var cancellationToken = _cts.Token;
await Task.Delay(timeout, cancellationToken);
// Check if the username exists
// Use the same cancellationToken if the API supports it
}
catch (TaskCanceledException)
{
// Ignore the exception
}
catch (Exception)
{
// Log the exception
}
}

警告CancellationTokenSource 是一次性的,但我没有在上面的示例中处理它。我不确定这是否是一个大问题。可能不是。这是一个相关问题:When to dispose CancellationTokenSource?

关于c# - 如何在 C# 中创建可重新触发的延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57663284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com