Skip to content

Instantly share code, notes, and snippets.

@altbodhi
Last active December 20, 2023 14:25
Show Gist options
  • Save altbodhi/6a159207957c82de4aa33fd569ad8bd7 to your computer and use it in GitHub Desktop.
Save altbodhi/6a159207957c82de4aa33fd569ad8bd7 to your computer and use it in GitHub Desktop.
throttled
@page "/"
@rendermode InteractiveServer
<input value="@query" @oninput="OnInput" />
@if (isGetItems)
{
<div style="font-style: italic;">поиск...</div>
}
else
{
@if (items.Count == 0)
{
<div style="font-weight: bold;">found nothing</div>
}
else
{
<h6>@items.Count</h6>
<ul>
@foreach (var item in items)
{
<li>@item.name</li>
}
</ul>
}
}
@code {
List<Item> items = new();
string query = "United States";
CancellationTokenSource cts = new CancellationTokenSource();
SemaphoreSlim mutex = new SemaphoreSlim(1);
bool isGetItems;
async Task OnInput(ChangeEventArgs args)
{
query = args.Value?.ToString() ?? string.Empty;
cts.Cancel();
isGetItems = false;
cts = new CancellationTokenSource();
await InvokeAsync(async () => await Task.Delay(1000, cts.Token)
.ContinueWith(async x => await mutex.WaitAsync(cts.Token))
.ContinueWith(async x => await GetItems(cts.Token)));
}
async Task GetItems(CancellationToken token)
{
try
{
isGetItems = true;
using (var http = new HttpClient())
{
items.Clear();
var url = string.Format("http://universities.hipolabs.com/search?country={0}", System.Net.WebUtility.UrlEncode(query));
var res = await http.GetFromJsonAsync<List<Item>>(url, token);
if (res != null)
items.AddRange(res);
}
}
finally
{
isGetItems = false;
mutex.Release();
await InvokeAsync(StateHasChanged);
}
}
public record Item(string name);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment