Skip to content
Merged
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
18 changes: 14 additions & 4 deletions src/MongoDB.Driver/Core/Misc/TaskExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,13 @@ static async Task WaitAsyncCore(Task task, TimeSpan timeout, CancellationToken c
{
if (!task.IsCompleted)
{
var timeoutTask = Task.Delay(timeout, cancellationToken);
await Task.WhenAny(task, timeoutTask).ConfigureAwait(false);
using (var timeoutCancellationTokenSource = cancellationToken.CanBeCanceled ?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to have a special case from non-cancelable token sources?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The previous special case created a regular CTS, which wasn’t necessary. I’ve updated it so non-cancelable tokens don’t create a CTS at all. the conditional now only avoids that unnecessary allocation.

CancellationTokenSource.CreateLinkedTokenSource(cancellationToken) : null)
{
var timeoutTask = Task.Delay(timeout, timeoutCancellationTokenSource?.Token ?? cancellationToken);
await Task.WhenAny(task, timeoutTask).ConfigureAwait(false);
timeoutCancellationTokenSource?.Cancel();
}
}

if (task.IsCompleted)
Expand All @@ -94,8 +99,13 @@ static async Task<TResult> WaitAsyncCore(Task<TResult> task, TimeSpan timeout, C
{
if (!task.IsCompleted)
{
var timeoutTask = Task.Delay(timeout, cancellationToken);
await Task.WhenAny(task, timeoutTask).ConfigureAwait(false);
using (var timeoutCancellationTokenSource = cancellationToken.CanBeCanceled ?
CancellationTokenSource.CreateLinkedTokenSource(cancellationToken) : null)
{
var timeoutTask = Task.Delay(timeout, timeoutCancellationTokenSource?.Token ?? cancellationToken);
await Task.WhenAny(task, timeoutTask).ConfigureAwait(false);
timeoutCancellationTokenSource?.Cancel();
}
}

if (task.IsCompleted)
Expand Down
63 changes: 63 additions & 0 deletions tests/MongoDB.Driver.Tests/Core/Misc/TaskExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
*/

using System;
#if !NET6_0_OR_GREATER
using System.Reflection;
#endif
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
Expand Down Expand Up @@ -105,6 +108,26 @@ await Record.ExceptionAsync(() => task.WaitAsync(TimeSpan.FromMilliseconds(5), C
exception.Should().BeOfType<TimeoutException>();
}

#if !NET6_0_OR_GREATER
[Theory]
[ParameterAttributeData]
public async Task WaitAsync_should_release_cancellation_token_registration_when_task_completes([Values(true, false)] bool generic)
{
using var cancellationTokenSource = new CancellationTokenSource();
var taskCompletionSource = new TaskCompletionSource<int>();
Task waitTask = generic ?
taskCompletionSource.Task.WaitAsync(Timeout.InfiniteTimeSpan, cancellationTokenSource.Token) :
((Task)taskCompletionSource.Task).WaitAsync(Timeout.InfiniteTimeSpan, cancellationTokenSource.Token);

GetCancellationCallbackCount(cancellationTokenSource).Should().Be(1);

taskCompletionSource.SetResult(42);
await waitTask;

GetCancellationCallbackCount(cancellationTokenSource).Should().Be(0);
}
#endif

[Theory]
[ParameterAttributeData]
public async Task WaitAsyncTResult_should_throw_on_negative_timeout([Values(true, false)] bool isPromiseTask)
Expand Down Expand Up @@ -210,6 +233,46 @@ private Task<TResult> CreateSubject<TResult>(TResult result, bool isPromise, Exc

return isPromise ? tcs.Task : Task.FromException<TResult>(exception);
}

#if !NET6_0_OR_GREATER
private static int GetCancellationCallbackCount(CancellationTokenSource cancellationTokenSource)
{
const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic;
var callbackListsField = typeof(CancellationTokenSource).GetField("m_registeredCallbacksLists", bindingFlags);
var callbackLists = (Array)callbackListsField.GetValue(cancellationTokenSource);
if (callbackLists == null)
{
return 0;
}

var count = 0;
foreach (var callbackList in callbackLists)
{
if (callbackList == null)
{
continue;
}

var fragment = callbackList.GetType().GetField("m_head", bindingFlags).GetValue(callbackList);
while (fragment != null)
{
var fragmentType = fragment.GetType();
var callbacks = (Array)fragmentType.GetField("m_elements", bindingFlags).GetValue(fragment);
foreach (var callback in callbacks)
{
if (callback != null)
{
count++;
}
}

fragment = fragmentType.GetField("m_next", bindingFlags).GetValue(fragment);
}
}

return count;
}
#endif
}
}

Loading