I implemented a debounce on input with CancellationTokenSource in Blazor server side app (.net core 3.0).
It works well with input delay as expected, but always writes errors in Debug Output,when typing:
Exception thrown: 'System.InvalidOperationException' in Microsoft.AspNetCore.Components.dlland when fast typing:
Exception thrown: 'System.Threading.Tasks.TaskCanceledException' in System.Private.CoreLib.dllDo you have any ideas how to fix it?
You can find the implementation here:https://blazorfiddle.com/s/ij9l55ne
Main page:
@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); }}Child component:
@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); }}