I want to use Parallel.ForEach to manipulate one set and return another. But I seem to get an empty one.And There is an asynchronous method that needs to be executed in Parallel.ForEach.
This is a console app with netcore2.2 in windows 10.
public static ConcurrentBag<int> GetList()
{
ConcurrentBag<int> result = new ConcurrentBag<int>() ;
List<int> list = new List<int> { 1, 2, 3 };
Parallel.ForEach(list, async i => {
await Task.Delay(i*1000);
result.Add(i * 2);
});
return result;
}
public static void Main(String[] args)
{
List<int> list = new List<int>();
var res = GetList();
list.AddRange(res);
Console.WriteLine("Begging.");
foreach (var item in list)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
I expect {2,4,6},but actual an empty one.