Parallel.ForEach

Costas

Administrator
Staff member
JavaScript:
Parallel.ForEach(dTCustomers.AsEnumerable(), new ParallelOptions { MaxDegreeOfParallelism = 5 }, dr =>
{
    string url = dr["url"].ToString();

    WebClient web = new WebClient();
    web.Encoding = Encoding.UTF8;
    Console.WriteLine(web.DownloadString(url));
}

https://www.c-sharpcorner.com/UploadFile/efa3cf/parallel-foreach-vs-foreach-loop-in-C-Sharp/

--

Multithreading made easy – Parallel ForEach

JavaScript:
//BAD - calling Add, then multiple threads may be resizing the array, or overwriting the same ‘slot’.
var barcodedImages = new ConcurrentBag<BarcodedImage>();
Parallel.ForEach(images, (image) =>
{
    string barcode = ReadBarcode(image);
    barcodedImages.Add(new BarcodedImage(barcode,image));
});

//workaround
object _lockObj = new object();
Parallel.ForEach(images, (image) =>
{
    string barcode = ReadBarcode(image);
    lock(_lockObj)
    {
      barcodedImages.Add(new BarcodedImage(barcode,image));
    }
});
 
Top