C# Microsoft.CodeAnalysis.CSharp.Scripting is not waiting for Parallel.For

81 Views Asked by At

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

1

There are 1 best solutions below

0
On BEST ANSWER

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.

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 into lock.

See also:

  • This answer for "When to use BlockingCollection and when ConcurrentBag instead of List<T>?"