Paulie
Paulie

Reputation: 131

ASP MVC app resets on long running thread

In my ASP MVC 5 app I have this database related operation that I've to perform once in month maybe and it takes about 30 - 60 minutes. I start this action like this:

    Repository dbForCategories = new Repository();
        dbForCategories.Database.CommandTimeout = 60000;
var t = Task.Factory.StartNew(async delegate
        {
            var crs = new ProductCategoryRelationsSetter(dbForCategories, categoryService);
            crs.AddProductsCategoriesRelations(oneLineTree);

        }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);

After about 5 minutes of working in background Im getting logged out of application. I think that the app resets because some static variables Im using are reset. In elmah i don't have any errors. I put my code in Try Catch block.

Only hope in you guys:)

Upvotes: 2

Views: 170

Answers (2)

Niels Filter
Niels Filter

Reputation: 4528

As @David mentioned, it's probably best to go the Windows Service route:

  • Write the item to a database table
  • Let a Windows Service poll the table every month (or however often you need it to).
  • If it finds a new item in the queue, let the Windows Service perform the operation.

Why not do Background threads in ASP.NET?

The server may recycle Application pool at some point and will not know to wait for your Task on a separate thread. (Discussed in this SO question)

.NET 4.5.2 onward. You can fire and forget short tasks

For interest sake you can use HostingEnvironment.QueueBackgroundWorkItem (see here) and the server will respect the background item and not recyle the App pool while it's busy, BUT ONLY for up to 90 seconds. anything longer and Windows Service is your best bet.

HostingEnvironment.QueueBackgroundWorkItem(ct => yourAsyncWork(ct));

Upvotes: 6

Andrew Edvalson
Andrew Edvalson

Reputation: 7878

Hangfire is wonderful for stuff like this.

https://www.nuget.org/packages/Hangfire/

Upvotes: 0

Related Questions