Is this use of Parallel.ForEach() thread safe?

后端 未结 3 597
庸人自扰
庸人自扰 2020-12-06 00:04

Essentially, I am working with this:

var data = input.AsParallel();
List output = new List();

Parallel.ForEach(dat         


        
3条回答
  •  伪装坚强ぢ
    2020-12-06 00:20

    Yes; List 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(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.

提交回复
热议问题