简体   繁体   中英

How do I properly handle a large background task in ASP.net Core 3?

This is a ASP.net Core 3 MVC application.

I am trying to extract an XML from a zipped file. I then need to parse that XML document and turn it into entities based on the the internal data. These XML files can be quite long. This application is meant to run on an internal network, self hosted, and will not be public facing.

I know that IHostedService and Worker Services are two ways to handle long tasks. However when I studied those options it seems they are used mostly for a repeated task. I need to run this task only when the file is uploaded.

Would it be good design to use an IHostedService or Worker Service? Perhaps something like would be handled within the model after all? Or is there some other better methodology of doing such tasks?

ASP.NET Core Performance Best Practices contains a section called Complete long-running Tasks outside of HTTP requests .

It says:

Most requests to an ASP.NET Core app can be handled by a controller or page model calling necessary services and returning an HTTP response. For some requests that involve long-running tasks, it's better to make the entire request-response process asynchronous.

Recommendations:

  • Do not wait for long-running tasks to complete as part of ordinary HTTP request processing.
  • Do consider handling long-running requests with background services or out of process with an Azure Function. Completing work out-of-process is especially beneficial for CPU-intensive tasks.
  • Do use real-time communication options, such as SignalR, to communicate with clients asynchronously.

aspnet.net's sample contains QueuedHostedService which is a non-time based BackgroundService .

The processing part looks like this:

private async Task BackgroundProcessing(CancellationToken stoppingToken)
{
    while (!stoppingToken.IsCancellationRequested)
    {
        var workItem = 
            await TaskQueue.DequeueAsync(stoppingToken);

        try
        {
            await workItem(stoppingToken);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, 
                "Error occurred executing {WorkItem}.", nameof(workItem));
        }
    }
}

The QueuedHostedSerivce is explained in Queued background tasks .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM