Last active
July 8, 2020 15:41
-
-
Save mburbea/001bae5f59faca2fea5bf69441a9957c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class Utils | |
{ | |
private static Func<T> Delay<T>(Func<Task, T> continuation, int ms, CancellationTokenSource? src = null) | |
where T : Task | |
{ | |
Interlocked.Exchange(ref src, new CancellationTokenSource())?.Cancel(); | |
return () => continuation(Task.Delay(ms, src!.Token)); | |
} | |
public static Func<Task<T>> Debounce<T>(Func<T> method, int ms = 250) | |
=> Delay(t => t.ContinueWith(_ => method, TaskContinuationOptions.OnlyOnRanToCompletion), ms); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class Utils | |
{ | |
public static Func<Task<T>> Debounce<T>(Func<T> method, int ms = 250, CancellationTokenSource? src = null) => delegate | |
{ | |
Interlocked.Exchange(ref src, new CancellationTokenSource())?.Cancel(); | |
return Task.Delay(ms, src!.Token).ContinueWith(_ => method(), TaskContinuationOptions.OnlyOnRanToCompletion); | |
}; | |
} |
amirburbea
commented
Jul 8, 2020
public static class Debounce
{
public static Func<Task<T>> Method<T>(Func<T> method, int ms = 250)
{
CancellationTokenSource? src = null;
return delegate
{
Interlocked.Exchange(ref src, new CancellationTokenSource())?.Cancel();
return Task.Delay(ms, src!.Token).ContinueWith(_ => method(), TaskContinuationOptions.OnlyOnRanToCompletion);
};
}
public static Func<Task> Method(Action method, int ms = 250)
{
CancellationTokenSource? src = null;
return delegate
{
Interlocked.Exchange(ref src, new CancellationTokenSource())?.Cancel();
return Task.Delay(ms, src!.Token).ContinueWith(_ => method(), TaskContinuationOptions.OnlyOnRanToCompletion);
};
}
}
One last go of shit...
public static class Debounce
{
public static Func<Task<T>> Method<T>(Func<T> method, int ms = 250) => Delay(method, ms);
public static Func<Task> Method(Action method, int ms = 250) => Delay(()=> { method(); return string.Empty; }, ms);
private static CancellationToken GetToken(ref CancellationTokenSource? src)
{
Interlocked.Exchange(ref src, new CancellationTokenSource())?.Cancel();
return src!.Token;
}
private static Func<Task<T>> Delay<T>(Func<T> method, int ms, CancellationTokenSource? src = null)
{
return () => Task.Delay(ms, GetToken(ref src)).ContinueWith(_ => method(), TaskContinuationOptions.OnlyOnRanToCompletion);
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment