0

I have more than one reader and I want to run all at the same time. I get reader IP and data from the same query in database use this query:

var deviceSetupsInfo = entities.LaneDeviceSetups
                  .Where(e => e.DeviceTypeId == 1)
                  .Select(e => new {
                     e.Ip,
                     e.LaneId,
                     e.TableName,
                     e.DeviceTypeId
                 }).ToList();
for (int i = 0; i < deviceSetupsInfo.Count; i++) {     
         Task.Run(() => new RFIDReader(
                            deviceSetupsInfo[i].Ip, 
                            deviceSetupsInfo[i].LaneId.Value,
                            deviceSetupsInfo[i].TableName, 
                            deviceSetupsInfo[i].DeviceTypeId.Value
                        )
         );
}

I want all return readers in [i] in loop run in the same time.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104

1 Answers1

0

parallel.foreach is the solution, lock is optional to avoid the edge cases

 object locker = new object();
    Parallel.ForEach(deviceSetupsInfo, (item) =>
                 {
                       //do stuff
                     
                 });
SIbghat
  • 281
  • 3
  • 5
  • 1
    The `lock` statement creates synchronized blocks of code, where only one thread can enter at a time. As such, it defeats the purpose of `Parallel.ForEach` IMHO. – Theodor Zoulias Feb 02 '21 at 15:00
  • If parallell processes are sharing same object due to any reason, it would break without a lock. Lock necer makes in synchrounous. It holds resources just for a fraction – SIbghat Feb 03 '21 at 05:36
  • thank you i use it ` new Thread(() => Parallel.ForEach(deviceSetupsInfo, device => )).Start();` – Ramy Atef Feb 03 '21 at 09:10