How to queue background tasks in ASP.NET Web API

前端 未结 4 433
無奈伤痛
無奈伤痛 2020-12-08 22:10

I have a webapi that is designed to process reports in a queue fashion. The steps the application takes are as follows:

  • Receive content
  • Map the conte
相关标签:
4条回答
  • 2020-12-08 22:53

    I like @Todd's solution. Just for the sake of completeness, but there's another option not mentioned yet:

    HostingEnvironment.QueueBackgroundWorkItem(cancellationToken =>
    {
        // Some long-running job
    });
    

    Note:

    "When ASP.NET has to recycle, it will notify the background work (by setting a CancellationToken) and will then wait up to 30 seconds for the work to complete. If the background work doesn’t complete in that time frame, the work will mysteriously disappear."

    And avoid using service methods with an injected DbContext here as this won't work.

    Sources: MariusSchulz and StephenCleary

    0 讨论(0)
  • 2020-12-08 22:59

    It's a NuGet package and it's called HangFire - https://github.com/HangfireIO/Hangfire. The tasks persist even beyond apppool recycling.

    0 讨论(0)
  • 2020-12-08 23:02

    If you use Asp.net Core,you can use IHostService.

    0 讨论(0)
  • 2020-12-08 23:08

    IMHO, your ASP.NET Web API application shouldn't run those background tasks by itself. It should only be responsible to receive the request, stick it inside the queue (as you indicated) and return the response indicating the success or failure of the received message. You can use variety of messaging systems such as RabbitMQ for this approach.

    As for the notification, you have a few options. You can have an endpoint which the client can check whether the processing is completed or not. Alternatively, you could provide a streaming API endpoint which your client can subscribe to. This way, the client doesn't have to poll the server; the server can notify the clients which are connected. ASP.NET Web API has a great way of doing this. The following blog post explains how:

    • Native HTML5 push notifications with ASP.NET Web API and Knockout.js

    You can also consider SignalR for this type of server to client notifications.

    The reason why background tasks are hard for ASP.NET Web API application is that you're responsible to keep the AppDomain alive. This is a hassle especially when you are hosting under IIS. The following blog posts explains really good what I mean:

    • Returning Early from ASP.NET Requests
    • The Dangers of Implementing Recurring Background Tasks In ASP.NET
    0 讨论(0)
提交回复
热议问题