Csharp: Parallel LINQ

https://devtut.github.io/csharp/parallel-linq-plinq.html#simple-example
https://github.com/PacktPublishing/Hands-On-Parallel-Programming-with-C-8-and-.NET-Core-3.0
https://gist.github.com/gfoidl/d8250ff11a5c70972cb8164622792ba1
https://github.com/lassevk/ObjectDumper
https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/order-preservation-in-plinq
LINQPad
https://github.com/giawa/RedPandaOS
http://www.albahari.com/nutshell/E9-CH22.aspx
https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-10
https://github.com/WolfgangOfner/CSharp-9.0/tree/master/CSharp9
https://github.com/apress/beg-cpp
https://github.com/Apress/beginning-cpp20
https://github.com/packtpublishing/beginning-cpp-programming

 

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Linq.Expressions;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;


//https://devtut.github.io/csharp/parallel-linq-plinq.html#simple-example
/// <summary>
/// geovindu 涂聚文 Geovin Du
/// </summary>
public partial class _Default : Page
{



    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        var sequence = Enumerable.Range(1, 10000).Select(x => -1 * x); // -1, -2, ...
        var evenNumbers = sequence.AsParallel()
                                  .OrderBy(x => x)
                                  .Take(5000)
                                  .AsUnordered()
                                  .Where(x => x % 2 == 0) // This line won't be affected by ordering
                                  .ToList();


        string wordLookupFile = Path.Combine(Path.GetTempPath(), "WordLookup.txt");

        if (!File.Exists(wordLookupFile))    // Contains about 150,000 words
            new WebClient().DownloadFile(
              "http://www.dusystem.com/allwords.txt", wordLookupFile);

        var wordLookup = new HashSet<string>(
          File.ReadAllLines(wordLookupFile),
          StringComparer.InvariantCultureIgnoreCase);

        string[] wordList = wordLookup.ToArray();

        // Here, we're using ThreadLocal to generate a thread-safe random number generator,
        // so we can parallelize the building of the wordsToTest array.
        var localRandom = new ThreadLocal<Random>
          (() => new Random(Guid.NewGuid().GetHashCode()));

        string[] wordsToTest = Enumerable.Range(0, 1000000).AsParallel()
          .Select(i => wordList[localRandom.Value.Next(0, wordList.Length)])
          .ToArray();

        wordsToTest[12345] = "woozsh";     // Introduce a couple
        wordsToTest[23456] = "wubsie";     // of spelling mistakes.

        var query = wordsToTest
          .AsParallel()
          .Select((word, index) => new IndexedWord { Word = word, Index = index })
          .Where(iword => !wordLookup.Contains(iword.Word))
          .OrderBy(iword => iword.Index);

        query.Dump();  //Dump



        string text = "Let’s suppose this is a really long string";

        int[] result =
          text.AsParallel().Aggregate(
            () => new int[26],             // Create a new local accumulator

            (localFrequencies, c) =>       // Aggregate into the local accumulator
    {
                int index = char.ToUpper(c) - 'A';
                if (index >= 0 && index <= 26) localFrequencies[index]++;
                return localFrequencies;
            },
            // Aggregate local->main accumulator
            (mainFreq, localFreq) =>
              mainFreq.Zip(localFreq, (f1, f2) => f1 + f2).ToArray(),

            finalResult => finalResult     // Perform any final transformation
          );                                 // on the end result.

        result.Dump();


        Parallel.ForEach(GetPokemon().OrderBy(p => p.Name), (p,s) =>
        {
            Response.Write(String.Format("Changing owner for {0} <br/>", p.Name));
            p.Owner = "Aaron";
        });

        Parallel.ForEach(GetPokemon().OrderBy(p => p.Name), (p, s, i) =>
        {
            Response.Write(String.Format("{0}. Changing owner for: {1}<br/>",i,p.Name));
            p.Owner = "Aaron";
        });

        GetPokemon().OrderBy(p => p.Name).AsParallel().ForAll((p) =>
        {
            Response.Write(String.Format("Changing owner for Du Name: {0}<br/>", p.Name));
            p.Owner = "Aaron";
        });


    }
    static IEnumerable<Pokemon> GetPokemon() => new List<Pokemon>
    {
        new Pokemon("Pikachu", "Electric", "Ash"),
        new Pokemon("Bulbasaur", "Grass", "Ash"),
        new Pokemon("Squirtle", "Water", "Ash"),
        new Pokemon("Charmander", "Fire", "Aaron"),
        new Pokemon("Gengar", "Ghost", "Ash"),
        new Pokemon("Snorlax", "Normal", "Ash"),
        new Pokemon("Geovin Du", "Psychic", "Ash"),
    };


    struct IndexedWord { public string Word; public int Index; }   


}

/// <summary>
/// 
/// </summary>
public static class Dumper
{
    public static string ToPrettyString(this object value)
    {
        return JsonConvert.SerializeObject(value, Formatting.Indented);
    }

    public static T Dump<T>(this T value)
    {
        Console.WriteLine(value.ToPrettyString());
        return value;
    }
}

/// <summary>
/// 
/// </summary>
public class Pokemon
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="name"></param>
    /// <param name="type"></param>
    /// <param name="owner"></param>
    public Pokemon(string name, string type, string owner)
    {
        Name = name;
        Type = type;
        Owner = owner;
    }
    /// <summary>
    /// 
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// 
    /// </summary>
    public string Type { get; set; }
    /// <summary>
    /// 
    /// </summary>
    public string Owner { get; set; }
}

 

posted @ 2022-01-09 16:55  ®Geovin Du Dream Park™  阅读(54)  评论(0编辑  收藏  举报