Search code examples
c#asp.net-coremediatr

HTTP request in pending status until MediatR notifications executed


var response = SaveOrderInDB();
OrderCreatedEvent orderCreatedEvent = new OrderCreatedEvent(x, y, z);            
_requestRouter.Publish(orderCreatedEvent);
return response;

By MediatR docs the notifications is "Fire and forget" feature. I do not use await since I want to return immediately "response" object to client Angular app after notification was published. However when I put breakpoint in notification handler I see in Chrom dev tools that request still in pending status, waits for notification to finish.

 public Task Handle(OrderCreatedEvent notification, CancellationToken cancellationToken)
    {
        return Task.CompletedTask; // Breakpoint is here 
    }

How can I not wait for notifications to finish? enter image description here


Solution

  • As mentioned in the comments, the breakpoint is preventing them from completing.

    If you don't believe this, change your NotificationHandler to something like:

    public async Task Handle(OrderCreatedEvent notification, CancellationToken cancellationToken)
    {
        await Task.Delay(5000);
    
        Console.Write("Done."); //put a breakpoint here
    }
    

    Put a breakpoint on the Console.Write method, then run your application, and call your endpoint.

    You'll see the response isn't pending, and after 5 seconds, your breakpoint is hit.
    (or "Done." is written to the console if you didn't set a breakpoint)