"is this use of parallel.foreach() thread safe?" Code Answer


yes; list<t> is not thread safe, so adding to it ad-hoc from arbitrary threads (quite possibly at the same time) is doomed. you should use a thread-safe list instead, or add locking manually. or maybe there is a parallel.tolist.

also, if it matters: insertion order will not be guaranteed.

this version is safe, though:

var output = new string[data.count];

parallel.foreach<string>(data, (line,state,index) =>
    string outputline = index.tostring();
    // ** do something with "line" and store result in "outputline" **

    // additionally, there are some this.invoke statements for updating ui
    output[index] = outputline;

here we are using index to update a different array index per parallel call.

By MSL on January 26 2022

Answers related to “is this use of parallel.foreach() thread safe?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.