jbogard / MediatR

Simple, unambitious mediator implementation in .NET
Apache License 2.0
11.19k stars 1.18k forks source link

Question: Why MediatR does not support ValueTasks ? #1046

Open AkhmedovEhson opened 5 months ago

AkhmedovEhson commented 5 months ago

Hi there!

First of all, I'd like to commend the team for the excellent work on MediatR. It's more than just a library, it's a well-defined pattern that has significantly improved the structure and maintainability of the projects.

However, I have encountered a performance issue when using MediatR in projects with a strong dependency on it. Specifically, when handling synchronous operations, we are required to return a Task, which introduces unnecessary garbage collection overhead and negatively impacts performance.

To mitigate this, would it be possible for MediatR to support ValueTask in addition to Task? This change could significantly enhance performance for synchronous operations by reducing the overhead associated with task allocation and garbage collection.

Thank you for considering this enhancement. Your work on MediatR is highly appreciated !

jbogard commented 4 months ago

What would this look like in terms of the API? Do you have a suggestion here?

grosch-intl commented 3 months ago

I would love to see something like HandleValueTaskAsync that returned a ValueTask

serber commented 2 months ago

@jbogard, in terms of the MediatR API, I think this would require a new interface to define a request handler that returns a ValueTask.

Outline code

public interface IValueTaskRequestHandler<in TRequest, TResponse>
    where TRequest : IRequest<TResponse>
{
    ValueTask<TResponse> Handle(TRequest request, CancellationToken cancellationToken);
}

And add some overhead or create new ValueTaskRequestHandlerWrapper for ValueTask.

Do you see any other options, and how necessary is this enhancement?

github-actions[bot] commented 2 weeks ago

This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 14 days.

driekus77 commented 2 weeks ago

Is IValueTaskRequestHandler still a todo? Still wanted?

remcoros commented 2 weeks ago

Having ValueTask in Mediatr does not make sense to me.

If you need the performance benefit of ValueTask when doing synchronous work only in a hot path, why do you use Mediatr in that hot path in the first place? You get instantly more performance benefits when cutting out Mediatr vs using ValueTask.

This request feels more like "because we can", not that it actually has any practical use-case.