Using Awaitable for Creating a Performant Debounce Method to be use in AutoComplete TextInput

Hi there,

Could you please advise on how to implement a debounce method without any allocations?

I’m using it for an autocomplete feature, so I need only the last event after a specified delay to trigger the listener. I tried using UniTask but wasn’t successful, and unfortunately, I haven’t received any responses there, and even AI-generated code didn’t work correctly.
Cysharp/UniTask#583

Thanks

I wrote this for a none Unity project, might be of use. It doesnt allocate in .NET 8 but you need to test it from Unity Mono runtime.

public class Throttler
{
    private readonly Timer _timer;
    private readonly Action _onThrottled;

    public Throttler(Action onThrottled)
    {
        _onThrottled = onThrottled;
        _timer = new Timer(Callback);
    }
    private void Callback(object? state)
    {
        _onThrottled();
    }

    public void Throttle()
    {
        _timer.Change(TimeSpan.FromMilliseconds(1), Timeout.InfiniteTimeSpan);
    }
}

edit: its a quick rewrite from this one, above is not the one I use. However this one do allocate

public class ThrottleHandler : IThrottleHandler
{
    private readonly Func<Task> _onThrottled = null!;
    private CancellationTokenSource _cancelSource = new();

    public ThrottleHandler(Func<Task> onThrottled)
    {
        _onThrottled = onThrottled;
    }

    public void Throttle()
    {
        _cancelSource.Cancel();
        _cancelSource = new CancellationTokenSource();

        Task.Run(async () =>
        {
            await Task.Delay(1);
            await _onThrottled();

        }, _cancelSource.Token);
    }
}
1 Like

Thank you! Initially, I used a CancellationTokenSource, but I looked for an alternative and found that UniTask offers reusable AutoResetUniTaskCompletionSource support. Unfortunately, I couldn’t get it to work due to my limited knowledge.