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

Asked

Viewed 380 times

2

I have the following code snippet in a method from my ASP.NET MVC application that deals with deleting 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 hoped that by doing the routine queuing on ThreadPool and leaving this method that the processing of the application (continuity) would occur smoothly.

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

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

This request is not finalized while, from what I can understand, this routine lined up in ThreadPool does not end. That is, my upload gif keeps showing up until finally the process ends and then the files and directories are listed.

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

What am I doing wrong?

1 answer

2


What am I doing wrong?

Using a gigantic critical region. As possibly other requisitions make use of it, the requisitions (which, by the way, are threads also) are blocked until the process ends. It’s the Philosophers' 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 fire the task and the rest of the application is not blocked. Some control mechanisms may be needed to ensure that some data in the critical region is not accessed while Hangfire works.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.