2

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:)

Paulie
  • 121
  • 2
  • 14
  • 5
    `"operation that I've to perform once in month maybe and it takes about 30 - 60 minutes"` - This is *not* a task for a web application. This is a task for a scheduled Console Application or perhaps a Windows Service. – David Aug 24 '15 at 13:08
  • or using a task scheduler library for ASP.NET MVC like as https://github.com/jgeurts/FluentScheduler – Luca Aug 24 '15 at 13:26

2 Answers2

6

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));
Community
  • 1
  • 1
Niels Filter
  • 4,430
  • 3
  • 28
  • 42
0

Hangfire is wonderful for stuff like this.

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

Andrew Edvalson
  • 7,658
  • 5
  • 26
  • 24