Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace CancelSearch
{
class Program
{
static void Main()
{
_userService = new UserService();
var query = string.Empty;
while (true)
{
var keyInfo = Console.ReadKey();
if (char.IsLetter(keyInfo.KeyChar))
{
query += keyInfo.Key;
TextChangedHandler(query);
}
else
{
Console.WriteLine("\nResetting query string");
query = string.Empty;
}
}
}
private static UserService _userService;
private static CancellationTokenSource _cts;
static async void TextChangedHandler(string text)
{
try
{
_cts?.Cancel(); // cancel previous search
}
catch (ObjectDisposedException) // in case previous search completed
{
}
using (_cts = new CancellationTokenSource())
{
try
{
await Task.Delay(TimeSpan.FromSeconds(1), _cts.Token);
var users = await _userService.SearchUsersAsync(text, _cts.Token);
Console.WriteLine($"\nGot users with IDs: {string.Join(", ", users)}");
}
catch (TaskCanceledException) // if the operation is cancelled, do nothing
{
}
}
}
}
class UserService
{
public async Task<IEnumerable<User>> SearchUsersAsync(string query, CancellationToken cancellationToken)
{
Console.WriteLine($"\nPerforming search with query {query}");
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
return new[] {new User()};
}
}
class User
{
public string Id { get; } = Guid.NewGuid().ToString();
public override string ToString()
{
return Id;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment