My situation is that I creating objects as well as saving and updating these objects in my database. I have an object Slot Plan which, by default, has around 123 slot objects and I have to write these into the database.
Depending on the case scenarios, i'd have to create many slot plans, so create and update could happen hundreds or thousands of times, which is time consuming. (creating 10 slot plans lasted around 3 minutes for me)
I understand that it really will take time, but how can I have the create and update run in the background and allow the user to continue navigate through the program to parts independent from the slots and slot plan?
Here's a snippet of my current code:
[HttpPost]
public ActionResult BookingRequestDetails(BookingRequestDetails model)
{
//Omitted code
if(shipmentinfo.ShipmentType.Equals("Export"))
CreateSlotPlan((DateTime)shipmentinfo.PickupDate, (DateTime shipmentinfo.PickupDateLast);
return RedirectToAction("Home");
}
public void CreateSlotPlan(DateTime firstdate, DateTime lastdate)
{
for (DateTime i = firstdate; i <= lastdate; i = i.AddDays(1))
{
SlotPlan slotplan = slotplanmanager.FindByDate(i);
if (slotplan == null)
{
slotplan = new SlotPlan { Date = i };
slotplanmanager.CreateSlotPlan(slotplan);
for (int j = 1; j <= 9; j++)
{
Slot slot = new Slot
{
Location = "A" + j
};
slotmanager.CreateSlot(slot);
slotplan.Slots.Add(slot);
slotplanmanager.UpdateSlotPlan(slotplan);
slotmanager.UpdateSlot(slot);
}
for (int j = 1; j <= 36; j++)
{
Slot slot = new Slot
{
Location = "B" + j
};
slotmanager.CreateSlot(slot);
slotplan.Slots.Add(slot);
slotplanmanager.UpdateSlotPlan(slotplan);
slotmanager.UpdateSlot(slot);
}
for (int j = 1; j <= 12; j++)
{
Slot slot = new Slot
{
Location = "C" + j
};
slotmanager.CreateSlot(slot);
slotplan.Slots.Add(slot);
slotplanmanager.UpdateSlotPlan(slotplan);
slotmanager.UpdateSlot(slot);
}
for (int j = 1; j <= 6; j++)
{
Slot slot = new Slot
{
Location = "D" + j
};
slotmanager.CreateSlot(slot);
slotplan.Slots.Add(slot);
slotplanmanager.UpdateSlotPlan(slotplan);
slotmanager.UpdateSlot(slot);
}
for (int j = 1; j <= 60; j++)
{
Slot slot = new Slot
{
Location = "E" + j
};
slotmanager.CreateSlot(slot);
slotplan.Slots.Add(slot);
slotplanmanager.UpdateSlotPlan(slotplan);
slotmanager.UpdateSlot(slot);
}
}
}
}
The code "return RedirectToAction("Home");" wouldn't execute unless "CreateSlotPlan(DateTime firstdate, DateTime lastdate)" is finished. I read that using async-await could solve my problem. But I don't know how to go about with asynchronous programming in my current code. Any help is appreciated.