How can I convert foreach code to Parallel.ForEach?
I'm not sure what you're looking for, but here's how you can accomplish it based on your query. Keep in mind that your logic inside the foreach block must be "paralleled-ready".
Paraller.foreach (archive.Entries,(pictureEntry)=>
{
if (string.Equals(pictureEntry.Name, imageName, StringComparison.OrdinalIgnoreCase))
{
//for reading the image
byte[] buffer;
long length = pictureEntry.Length;
buffer = new byte[length];
pictureEntry.Open().Read(buffer, 0, (int)length);
myImage.Source = ImageSource.FromStream(() => new MemoryStream(buffer));
}
});
You can refer official documentation also - [1]:https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-write-a-simple-parallel-foreach-loop?redirectedfrom=MSDN
How can I convert this foreach code to Parallel.ForEach?
string[] lines = File.ReadAllLines(txtProxyListPath.Text);
List<string> list_lines = new List<string>(lines);
Parallel.ForEach(list_lines, line =>
{
//Your stuff
});
Convert foreach to Parallel.ForEach
I would use an overload of the Parallel.ForEach
so your i
parameter is provided by the foreach method:
Parallel.ForEach(DT.Rows.OfType<System.Data.DataRow>(), (DataRow row2, ParallelLoopState loopState, long i) =>
{
try {
bool check = (urlcheck(dataGridView.Rows[(int)i].Cells[2].Value.ToString()));
if (check == true)
ExecuteQuery("");
else
ExecuteQuery("");
}
catch{ }
});
For the OfType<>
method you need to add using System.Linq
to your using statements.
Now the index (i
) is automaticly assigned by the method call so you don't have to worry about thread safety of i
.
How to convert foreach to Parallel.Foreach in c#
This is because the foreach
is converting the items in the ArrayList
to string
from an object
. All the items in an ArrayList
are object
at compile time, and object
doesn't have a method called StartsWith
.
In this case:
foreach (string item in list)
item
is converted into a string
from object
.
To do the same you will need to perform the conversion yourself e.g.
Parallel.ForEach(list.OfType<string>().ToArray(), item ....
Or .Cast<string>
instead of OfType
if you want to fail at runtime if there's a non-string instance in your list
.
Alternatively use a generic list such as List<String>
to avoid runtime casting.
Foreach into Parallel.Foreach c#
I am not sure what are you asking for but based on your question, here is how you can do that. Keep in mind that your logic inside must be "paralleled-ready".
Parallel.ForEach(storeCodesData, (storeData) =>
{
string[] storeDataSplit = storeData.Split(',');
if (storeDataSplit[0] != "")
{
Store store1 = new Store { StoreCode = storeDataSplit[0], StoreLocation = storeDataSplit[1] };
stores.Add(store1);
storename.Add( storeDataSplit[1]);
}
PopulateListViewItems(storeDataSplit[0]);
});
Parallel.ForEach loop is not working it skips some and double do others
Thanks to sedat-kapanoglu, I found the problem is really about thread safety. The solution was to change every List<T>
to ConcurrentBag<T>
.
For everyone, like me, The solution of "parallel not working with collections" is to change from System.Collections.Generic
to System.Collections.Concurrent
Related Topics
Determine the Number of Lines Within a Text File
How to Seed a Random Class to Avoid Getting Duplicate Random Values
At the End of an Async Method, Should I Return or Await
Type or Namespace Name Does Not Exist
New Keyword in Method Signature
Gradient Circles for Map Generator
Check for Column Name in a SQLdatareader Object
How to Get the File Size from Http Headers
Regular Expression Groups in C#
No Output to Console from a Wpf Application
When to Use Blockingcollection and When Concurrentbag Instead of List<T>
Catch Exception That Is Thrown in Different Thread
What Operations Are Atomic in C#
Using Linq to Get the Last N Elements of a Collection
Prevent .Net Garbage Collection for Short Period of Time