Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Task delay with infinite timespan is leaking memory #26

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,13 @@ public Task ExecuteAsync(Func<Task> function, CancellationToken cancellationToke
/// </summary>
public async Task ExecuteAsync(Priority priority, Func<Task> function, CancellationToken cancellationToken = default)
{
using (var delayTaskCancellationSource = new CancellationTokenSource())
using (var linkedCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, delayTaskCancellationSource.Token))
using (var item = await _taskManager.AcquireAsync(priority, cancellationToken))
{
try
{
var delayTask = Task.Delay(Timeout.Infinite, cancellationToken);
var delayTask = Task.Delay(Timeout.Infinite, linkedCancellationSource.Token);

var resultTask = await Task.WhenAny(
function.Invoke(),
Expand All @@ -73,6 +75,14 @@ public async Task ExecuteAsync(Priority priority, Func<Task> function, Cancellat
{
cancellationToken.ThrowIfCancellationRequested();
}
else
{
// Stop delayTask, otherwise it is kept indefinetly and leaks CancellationTokenRegistration (DelayPromiseWithCancellation)
delayTaskCancellationSource.Cancel();

// await ensures cancellation was received and accepted before we dispose CancellationTokenSource
await delayTask.IgnoreWhenCancelled();
}

if (resultTask.IsFaulted && resultTask.Exception is not null)
{
Expand Down
22 changes: 22 additions & 0 deletions src/Farfetch.LoadShedding/Tasks/TaskExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System;
using System.Threading.Tasks;

namespace Farfetch.LoadShedding.Tasks
{
internal static class TaskExtensions
{
public static async Task IgnoreWhenCancelled(this Task task)
{
if (!task.IsCanceled)
{
try
{
await task.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
}
}
}
}
Loading