gpt4 book ai didi

blazor - 在 Blazor 服务器端使用 CancellationTokenSource 去抖动实现

转载 作者:行者123 更新时间:2023-12-02 04:22:29 29 4
gpt4 key购买 nike

我在 Blazor 服务器端应用程序(.net core 3.0)中使用 CancellationTokenSource 对输入实现了去抖动。

它按预期在输入延迟下运行良好,但总是在调试输出中写入错误,
打字时:

Exception thrown: 'System.InvalidOperationException' in Microsoft.AspNetCore.Components.dll

当快速打字时:
Exception thrown: 'System.Threading.Tasks.TaskCanceledException' in System.Private.CoreLib.dll

你有什么想法如何解决吗?

你可以在这里找到实现:
https://blazorfiddle.com/s/ij9l55ne

主页:
@page "/"
@using System.Threading
@using System.Threading.Tasks

<MyChildComponent OnTyping="async e => await OnTypingAsync(e)"/>
<div>@result</div>

@code {
string result;

public async Task OnTypingAsync(string myText)
{
await Task.Delay(1);//call GetDataAsync(myText) method

result = myText;
await InvokeAsync(StateHasChanged);
}
}

子组件:
@using System.Threading
@using System.Threading.Tasks

<input type="text" @oninput="async e => await OnInput(e)" />

@code {
[Parameter] public EventCallback<string> OnTyping { get; set; }

CancellationTokenSource Cts = new CancellationTokenSource();
CancellationToken Ct;

public async Task OnInput(ChangeEventArgs e)
{
Cts.Cancel();
Cts = new CancellationTokenSource();
Ct = Cts.Token;

await Task.Delay(500, Ct).ContinueWith(async task =>
{
if (!task.IsCanceled) {
await OnTyping.InvokeAsync(e.Value.ToString());
}
}, Ct);
}
}

最佳答案

javiercn 在我注册的 github issue 上提供了如何解决这个问题的好主意:
https://github.com/aspnet/AspNetCore/issues/16524#issuecomment-546847682

  • 使用取消 token 时,您需要始终捕获 OperationCanceledException。
  • 您应该避免在您的方法中使用 continue with 因为您没有捕获 SynchronizationContext 并且当您尝试从继续回调更新 UI 时会产生错误。
  • 关于blazor - 在 Blazor 服务器端使用 CancellationTokenSource 去抖动实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58568403/

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