I am using Parallel.ForEach Loop
with my collection and i saw that this process my collection in some arbitrary oder or maybe divide my collection into pices so Is it possible that Parallel.ForEach
Loop will handle all my collection in order ?
Edit
list<MyData> mylist;
private void StartTransmit(ObservableCollection<WiresharkFile> files)
{
cancellationTokenSource = new CancellationTokenSource();
var token = cancellationTokenSource.Token;
Task.Factory.StartNew(() =>
{
try
{
Parallel.For(0, files.Count, new ParallelOptions { MaxDegreeOfParallelism = 5},
i =>
{
if (token.IsCancellationRequested)
return;
//do work...
files[i].ProcessFile();
});
}
catch (Exception e)
{ }
}, cancellationTokenSource.Token,
TaskCreationOptions.None,
TaskScheduler.Default).ContinueWith(
t =>
{
}
);
}
Parallel.ForEach
is made to work parallel. if your collection has very big logic which requires outside resources then only it will work in random order because it does not wait for one iteration to get complete. If you want to process collection in order then Paraller.ForEach
is bad idea. Go with foreach
.
One of the solution could be setting MaxDegreeOfParallelism
property of ParallelOptions
class to 1. like
Parallel.For(0, 1000, new ParallelOptions { MaxDegreeOfParallelism = 1 },
i =>
{
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.