Parallel.ForEach problem with synchronization

Viewed 45

In parallel, I read from the LIST(adresses) of devices that I will connect to and from which they will generate an image. If I do it sequentially everything is fine. If I use a parallel approach, I start to generate images incorrectly - or rather, I name each image according to the name of the device, and this is where the problem arises - the names and images are mixed up.

Parallel.ForEach(adresses, new ParallelOptions{MaxDegreeOfParallelism=Convert.ToInt32(Math.Ceiling((Environment.ProcessorCount * 0.75) * 2.0)) },
        device=>
        {   
           _sensor = SensorFactory.ConnectSensor(new IPEndPoint(IPAddress.Parse(device), Properties.Settings.Default.PortNo));
           sensorName = _sensor.DeviceName.ToString();
           _dataChangeEventHandler = _sensor.Subscribe(DataChangeEventHandler);
           _sensor.Tick(); //requests a connection to the device, another method is called that requests, generates and saves an image to fileshare
         }
       );

Does anyone have any advice on where the problem might be and how to solve it or change the concept altogether?

0 Answers
Related