Routine included in ThreadPool to run in "background" does not let the application continue running

2

I have the following code snippet in a method of my ASP.NET MVC application that tries to delete the directories and their files.

// efetuo processos de remoção de arquivos do banco de dados
await Context.SaveChangesAsync();

var itens = diretorios.Select(x => new
{
    x.Id,
    x.AreaId
});

ThreadPool.QueueUserWorkItem(x =>
{
    var directories = itens
        .Select(item => Configurations.Documents.PublicDirectory(item.Id, item.AreaId))
        .Where(Directory.Exists);

    foreach (var directory in directories)
    {
        try
        {
            Directory.Delete(directory, true);
        }
        catch
        {
            // Ignore                   
        }
    }
});

return RedirectToAction("Index");

I expected that by queuing the routine in ThreadPool and exiting this method that application (continuity) processing would occur without problems.

So it was during debugging and testing, no problem. However, it already hangs on my web server.

The redirection to Action Index works, however, in Index there is an Ajax request to re-list the files (these are not even fetched on disk, but in the database).

This request is not terminated whereas, as far as I can understand, this routine queued at ThreadPool does not end. That is, my loading gif keeps popping up until finally the process terminates and then the files and directories are listed.

The application does not open in any other browser while the process does not finish.

What am I doing wrong?

    
asked by anonymous 06.04.2016 / 18:37

1 answer

2
  

What am I doing wrong?

Using a gigantic critical region. As possibly other requests make use of it, the requests (which, incidentally, are threads too) are blocked until the process terminates. It is the Philosopher's Dinner in a Web approach .

I do not think this is the best way to do it. In ASP.NET MVC applications, the best way to establish this parallelism you want is by using some scheduling library, like Hangfire .

Hangfire allows you to launch the task and the rest of the application is not blocked. Some control mechanisms may be needed to ensure that some critical region data is not accessed while Hangfire works.

    
06.04.2016 / 18:59