I tried a very simple test with Microsoft.CodeAnalysis.CSharp.Scripting
with the following code snippet:
var code = @"
var myList = new List<string>();
Parallel.For(0, 300, i =>
{
myList.Add("""" + i);
});
return myList;";
var scrOptions = ScriptOptions.Default
.WithReferences("System", "System.Threading", "ScriptEngineTest")
.WithImports("System", "System.Threading.Tasks", "System.Collections.Generic")
.WithLanguageVersion(LanguageVersion.Latest);
var script = CSharpScript.Create<List<string>>(code, scrOptions);
script.Compile();
var myList = (await script.RunAsync()).ReturnValue;
The code is executed fine but not waiting until the Paralell.For has finished - my return list has different counts, but not the full 300 items.
Is this a bug or maybe not really supported?
THX in advance
This does not prove that
Paralell.For
is not finished.List<T>
is not thread-safe and you see the standard race condition effect. Use thread-safe collection or wrap the collection modification intolock
.See also:
BlockingCollection
and whenConcurrentBag
instead ofList<T>
?"