C# How to change value within Parallel.Foreach

Asked

Viewed 122 times

3

I am performing a processing inside an array of strings (lines of a file . txt).

For performance reasons, I’m using the Parallel.ForEach, but there was a need to change the values of some lines that were not processed.

I wonder if it is possible to change the value of a list element within the foreach

Follows code

List<string> linhas = new List<string>();

// imaginem essas linhas com varios valores

Parallels.Foreach(linhas, (linha) => {

    //algum processamento

    linha = "não processado"; //como resolver isso


});

My tests proved that it doesn’t work, but I’d like to know if there’s a possibility to do this.

  • Parallels.Foreach will have a negative impact on performance in relation to foreach classic. Also, you cannot change the collection that is iterating within the For Each block.

  • 2

    @Cypherpotato "will have a negative impact on performance" as well? There will be situations where this is true but not at all.

  • Well, regardless, you still won’t be able to change any element of the collection that is iterating within the For Each block. What you can do is use Parallels.For and change by index in the object collection.

1 answer

4


Browser other questions tagged

You are not signed in. Login or sign up in order to post.