SpiritBob
SpiritBob

Reputation: 2702

Is this particular Parallel.For() loop thread-safe?

Parallel.For(0, someStringArray.Count, (i) =>
{
    someStringArray[i] = someStringArray[i].Trim();
});

I'm sure that only reading through a collection with Parallel.For is considered thread-safe.

EDIT: The array is not being accessed through other parts of code.

Upvotes: 0

Views: 149

Answers (1)

mm8
mm8

Reputation: 169420

Is this particular Parallel.For() loop thread-safe?

Depending on the implementation of the type of someStringArray, it is as long as you are not modiying the collection itself while enumerating.

At no time are two threads modifying the same element in the collection in your example.

Generally speaking, collections are not considered thread-safe because their internal logic may fail if you for example read an item from one thread while another thread adds an item and cause the collection to resize (and items to get copied) in the middle of the read operation.

This shouldn't happen with fixed-size arrays though. List<T> uses an array under the hood but that's an implementation detail that you shouldn't really rely on in the general case.

Upvotes: 1

Related Questions