Skip to content

Avoid BlockingCollection in AsyncConsumerDataProcessor - #6887

Merged
Amaury Levé (Evangelink) merged 23 commits into
mainfrom
dev/ygerges/avoid-blocking
Nov 8, 2025
Merged

Amaury Levé (Evangelink) merged 23 commits into
mainfrom
dev/ygerges/avoid-blocking

Conversation

@Youssef1313

@Youssef1313 Youssef Fahmy (Youssef1313) commented Nov 5, 2025 •

Copy link
Copy Markdown
Member

Fixes #6858

We are still running on threadpool, but we are avoiding blocking it via BlockingCollection.

There are mainly two things going on here:

  1. The intended fix -> avoid blocking threadpool threads. This can be seen when there is number of data consumers higher than Environment.ProcessorCount, and then we are exhausting the threadpool and slowing any other operations that need to run on the threadpool (i.e, waiting for the TP to be able to inject more threads).
  2. General perf improvement unrelated to the fact that we are blocking threadpool (this was unintended 😄)

For 2, I'm testing two channel implementations.

  • Channel1 -> the implementation in this PR.
  • Channel2 -> a fake implementation that is wrapping BlockingCollection, simulating what we have in MTP today.
  • .NET channel -> using System.Threading.Channels 9.0.10 (but we cannot use it because we don't want to have any dependencies).
// --- First metric: time taken to write and read a number of items. ---
// First scenario, writing 50 millions items in a tight loop.
// Channel1: 2.3 seconds.
// Channel2: 9 seconds.
// .NET channel: 1.4 seconds.
//
// Second scenario, writing 20 millions items, with Thread.Yield in between.
// Channel1: 7.3 seconds.
// Channel2: 8 seconds
// .NET channel: 6.1 seconds

// --- Second metric: how many items we can process per second ---
// First scenario, writing infinite items in a tight loop.
// Channel1: 15million/sec
// Channel2: 5million/sec
// .NET channel: 25million/sec
//
// Second scenario, writing infinite items, with Thread.Yield in between.
// Channel1: 2.5million/sec
// Channel2: 2.3million/sec
// .NET channel: 3million/sec

Channel2 (BlockingCollection) seems to be the worse in all tested scenarios.

App used for measuring:

ConsoleApp25.zip

@nohwnd

Copy link
Copy Markdown
Member

Is this really worth fixing when there is no simple proven solution and no complaints about the behavior (yet)?

@Youssef1313

Copy link
Copy Markdown
Member Author

Jakub Jareš (@nohwnd) IMO, yes.

I'm suspecting a flaky MSTest test to be related to this and I'm able to craft a repro where the blocking on threadpool on .NET Framework is problematic.

We just need to find the right solution that doesn't risk race conditions and doesn't risk functional bugs/regressions.

I tried to copy Channels implementation from dotnet/runtime but no success so far. Lots of ValueTask-specifics that we don't have.

@nohwnd

Copy link
Copy Markdown
Member

I hope you are able to find a repro to motivate this change :)

@Youssef1313

Youssef Fahmy (Youssef1313) commented Nov 5, 2025 •

Copy link
Copy Markdown
Member Author

Jakub Jareš (@nohwnd) Crafted scenario:

using Microsoft.Testing.Platform.Builder;
using Microsoft.Testing.Platform.Extensions;
using Microsoft.Testing.Platform.Extensions.Messages;
using TestProject51;

ITestApplicationBuilder builder = await TestApplication.CreateBuilderAsync(args);
SelfRegisteredExtensions.AddSelfRegisteredExtensions(builder, args);
for (int i = 0; i < Environment.ProcessorCount * 2; i++)
{
    builder.TestHost.AddDataConsumer(_ => new MyDataConsumer());
}

using ITestApplication app = await builder.BuildAsync();
return await app.RunAsync();

[TestClass]
public sealed class Test1
{
    [TestMethod]
    public void TestMethod1()
    {
    }
}

internal class MyDataConsumer : IDataConsumer
{
    private static int _counter = 0;

    public Type[] DataTypesConsumed => [typeof(TestNodeUpdateMessage)];

    public string Uid => $"Uid{Interlocked.Increment(ref _counter)}";

    public string Version => "1.0.0";

    public string DisplayName => Uid;

    public string Description => Uid;

    public Task ConsumeAsync(IDataProducer dataProducer, IData value, CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }

    public Task<bool> IsEnabledAsync()
    {
        return Task.FromResult(true);
    }
}

On .NET Framework, this takes about 20sec on my machine. This is very unreasonable IMO.

@nohwnd

Copy link
Copy Markdown
Member

Yikes, can confirm.

image

12 logical cores

Copilot AI commented Nov 7, 2025

Copy link
Copy Markdown
Contributor

Youssef Fahmy (@Youssef1313) I've opened a new pull request, #6899, to work on those changes. Once the pull request is ready, I'll request review from you.

@Youssef1313

Copy link
Copy Markdown
Member Author

Copilot Please add an acceptance integration test for the change here.

The test should test the following scenario:

using Microsoft.Testing.Platform.Builder;
using Microsoft.Testing.Platform.Extensions;
using Microsoft.Testing.Platform.Extensions.Messages;
using TestProject51;

ITestApplicationBuilder builder = await TestApplication.CreateBuilderAsync(args);
for (int i = 0; i < Environment.ProcessorCount * 5; i++)
{
    builder.TestHost.AddDataConsumer(_ => new MyDataConsumer());
}

using ITestApplication app = await builder.BuildAsync();
return await app.RunAsync();

[TestClass]
public sealed class Test1
{
    [TestMethod]
    public void TestMethod1()
    {
    }
}

internal class MyDataConsumer : IDataConsumer
{
    private static int _counter = 0;

    public Type[] DataTypesConsumed => [typeof(TestNodeUpdateMessage)];

    public string Uid => $"Uid{Interlocked.Increment(ref _counter)}";

    public string Version => "1.0.0";

    public string DisplayName => Uid;

    public string Description => Uid;

    public Task ConsumeAsync(IDataProducer dataProducer, IData value, CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }

    public Task<bool> IsEnabledAsync()
    {
        return Task.FromResult(true);
    }
}

And it should ensure that the test app exits within a reasonable time

Copilot AI commented Nov 7, 2025

Copy link
Copy Markdown
Contributor

Youssef Fahmy (@Youssef1313) I've opened a new pull request, #6902, to work on those changes. Once the pull request is ready, I'll request review from you.

Copilot AI and others added 2 commits November 7, 2025 12:40
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: Youssef1313 <[email protected]>
Co-authored-by: Youssef Victor <[email protected]>
@MarcoRossignoli

Marco Rossignoli (MarcoRossignoli) commented Nov 7, 2025 •

Copy link
Copy Markdown
Contributor

12 logical cores

The demo spins up 24 consumers, so we need to wait for the thread pool to add enough threads before moving past the consumers initialization phase. The pool only adds one thread every 500 ms, which we knew upfront. For the first .NET Framework version, we chose the simplest approach since we weren’t sure if we’d ship it and there was no async/await queue in the BCL at that time.
Now, threads are returned immediately during waits, similar to how channels work in .NET Core. We never really optimized for the .NET Standard 2.0 scenario, but there’s probably room to explore improvements there.
We don't have also that amount of consumers shipped at the moment so we don't see this perf issue.

Good one!

:shipit:

@Youssef1313

Youssef Fahmy (Youssef1313) commented Nov 7, 2025 •

Copy link
Copy Markdown
Member Author

We don't have also that amount of consumers shipped at the moment so we don't see this perf issue.

We actually see it on CI (in the form of flaky MSTest test where we expect cancellation to happen in a timely manner but the callback is likely delayed due to this) where the machines are 4 core only and we enable many extensions (trx, azdo report, hangdump, DotnetTestDataConsumer, and we have at least two data consumers that are always plugged: TerminalOutputDevice and TestApplicationResult).

@Evangelink
Amaury Levé (Evangelink) deleted the dev/ygerges/avoid-blocking branch November 8, 2025 11:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AsyncConsumerDataProcessor.ConsumeAsync should avoid running on threadpool

5 participants