Calling API using Parallel.ForEach not processing all records

20 Views Asked by At

In below code driverList will have 100 unique drivers and based on the start date and end date, n number of driver activity will be generated for n number of drivers.

Here for example if driverList has 30 unique drivers and start date and end dates have a difference of two weeks then the total request that are sent to API is around 10K and it takes a lot of time to process. I would like to know if there is a way to process driverList parallely(i.e: Process multiple drivers to api at the same time).

I tried Parallel.ForEach but its not process all the requests, after some 50 requests i get no connection found.

Any lead is much appreaciated.

`foreach (var driver in driverList)
{
DateTime startDate = startTime;
DateTime endDate = endTime;
while (startDate.Date != endDate.Date)
{
    var driveTime = Constants.Constants.DrivingTimeInMinutes.OrderBy(i => Guid.NewGuid())
        .ToList();
    var restTime = Constants.Constants.DrivingTimeInMinutes.OrderBy(i => Guid.NewGuid())
        .ToList();

    Random rand = new Random();

    var activity = Constant.Activity[rand.Next(Constant.Activity.Length)];

    DriverActivity driverActivity = new DriverActivity()
    {
        DriverId = driver.DriverId,
        DriverName = driver.FirstName + " " + driver.LastName,
        Date = startDate.Date.ToString("yyyy-MM-dd"),
        Activity = activity,
    };

    switch (activity)
    {
        case "Driving":
            driverActivity.StartTime = startDate;
            driverActivity.EndTime =
                driverActivity.StartTime.AddMinutes(driveTime[rand.Next(driveTime.Count)]);
            break;
        case "REST":
            driverActivity.StartTime = startDate;
            driverActivity.EndTime =
                driverActivity.StartTime.AddMinutes(restTime[rand.Next(restTime.Count)]);
            break;
        default:
            driverActivity.StartTime = startDate;
            driverActivity.EndTime =
                driverActivity.StartTime.AddMinutes(
                    Constants.Constants.OtherTimeInMinutes[
                        rand.Next(Constants.Constants.OtherTimeInMinutes.Length)]);
            break;
    }

    startDate = driverActivity.EndTime;
    await ApiClient.UpdateDriverAcitivity(driverActivity);
    }
    Console.WriteLine($"Processed Driver : {driver.DriverId} successfully");
    }`
0

There are 0 best solutions below