I have a MVC website using EF for data access. The app takes in data, runs a series of calculations and stores the results. Each batch of data can have several thousand records and the calculations take on average 30 seconds - I want to run all this in the background.
So far I have Hangfire in place to trigger the batches. I then do:
var queue = new Queue<MyItem>();
// queue is populated ...
while (queue.Any())
{
var item = queue.Dequeue();
var task = Task.Run(() =>
{
using (var context = new MyDbContext())
{
context.MyItem.Add(item);
// Run Calculations
try {
context.SaveChanges();
}
catch {
// Log error
}
}
}
}
When a batch is running the site either becomes completely unresponsive, or I receive 'The underlying provider failed on Open' errors.
Is there a better approach to this?
MyDbContext
has async support you should useawait context.SaveChangesAsync()
. This can free up your threads to handle more requests.