Using 'AsParallel()' / 'Parallel.ForEach()' guidelines?

前端 未结 4 1862
说谎
说谎 2021-01-30 20:52

Looking for a little advice on leveraging AsParallel() or Parallel.ForEach() to speed this up.

See the method I\'ve got (simplified/bastardized

4条回答
  •  滥情空心
    2021-01-30 21:14

    Several points.

    writing just countriesAndAliases.AsParallel() is useless. AsParallel() makes part of Linq query that comes after it execute in parallel. Part is empty, so no use at all.

    generally you should repace foreach with Parallel.ForEach(). But beware of not thread safe code! You have it. You can't just wrap it into foreach because List.Add is not thread safe itself.

    so you should do like this (sorry, i didn't test, but it compiles):

            return countriesAndAliases
                .AsParallel()
                .SelectMany(s => 
                    IsCountryNotAlias(s)
                        ? Enumerable.Repeat(s,1)
                        : AliasCountryLists[s]
                    ).Distinct();
    

    Edit:

    You must be sure about two more things:

    1. IsCountryNotAlias must be thread safe. It would be even better if it is pure function.
    2. No one will modify AliasCountryLists in a meanwhile, because dictionaries are not thread safe. Or use ConcurrentDictionary to be sure.

    Useful links that will help you:

    Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4

    Parallel Programming in .NET 4 Coding Guidelines

    When Should I Use Parallel.ForEach? When Should I Use PLINQ?

    PS: As you see new parallel features are not as obvious as they look (and feel).

提交回复
热议问题