Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      May 14, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      May 14, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      May 14, 2025

      How To Prevent WordPress SQL Injection Attacks

      May 14, 2025

      I test a lot of AI coding tools, and this stunning new OpenAI release just saved me days of work

      May 14, 2025

      How to use your Android phone as a webcam when your laptop’s default won’t cut it

      May 14, 2025

      The 5 most customizable Linux desktop environments – when you want it your way

      May 14, 2025

      Gen AI use at work saps our motivation even as it boosts productivity, new research shows

      May 14, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Strategic Cloud Partner: Key to Business Success, Not Just Tech

      May 14, 2025
      Recent

      Strategic Cloud Partner: Key to Business Success, Not Just Tech

      May 14, 2025

      Perficient’s “What If? So What?” Podcast Wins Gold at the 2025 Hermes Creative Awards

      May 14, 2025

      PIM for Azure Resources

      May 14, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Windows 11 24H2’s Settings now bundles FAQs section to tell you more about your system

      May 14, 2025
      Recent

      Windows 11 24H2’s Settings now bundles FAQs section to tell you more about your system

      May 14, 2025

      You can now share an app/browser window with Copilot Vision to help you with different tasks

      May 14, 2025

      Microsoft will gradually retire SharePoint Alerts over the next two years

      May 14, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Best of…: Classic WTF: For Each Parallel

    Best of…: Classic WTF: For Each Parallel

    July 4, 2024

    It’s a holiday in the US today, where we celebrate with a lot of explosive-induced accidents and emergencies. Instead of holding a cherry bomb until it’s too late, let’s instead look at some explosively parallel code. Original. —Remy

    Parallel programming is hard. For all the advancements and tweaks we’ve made to our abstractions, for all the extra cores we’ve shoved into every CPU, deep down, software still carries the bias of the old uni-tasking model.

    Aleksei P works on a software package that is heavily parallel. As such, when interviewing, he talks to candidates about their experience with .NET’s Task objects and the async/await keywords.

    One candidate practically exploded with enthusiasm when asked. “I’ve just finshed a pretty large text processing project that reads a text file in parallel!” They whipped out a laptop, pulled up the code, and proudly showed it to Aleksei (and gave Aleksei a link to their repo for bonus points).

    public async Task<IDictionary<string, int>> ParseTextAsync(string filePath, ParamSortDic dic)
    {
    if (string.IsNullOrEmpty(filePath))
    {
    throw new ArgumentNullException(nameof(filePath));
    }

    if (Path.GetExtension(filePath)!=“.txt”)
    {
    throw new ArgumentException(“Invalid filetype”);
    }
    Dictionary<ParamSortDic, Func<IDictionary<string, int>, IOrderedEnumerable<KeyValuePair<string, int>>>> sorting =
    new Dictionary<ParamSortDic, Func<IDictionary<string, int>, IOrderedEnumerable<KeyValuePair<string, int>>>>
    {
    {ParamSortDic.KeyAsc,word=> word.OrderBy(ws=>ws.Key)},
    {ParamSortDic.KeyDesc,word=>word.OrderByDescending(ws=>ws.Key)},
    {ParamSortDic.ValueAsc,word=>word.OrderBy(ws=>ws.Value)},
    {ParamSortDic.ValueDesc,word=>word.OrderByDescending(ws=>ws.Value)},
    };
    var wordCount = new Dictionary<string, int>();
    object lockObject = new object();
    using (var fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read))
    {
    using (var streamReader = new StreamReader(fileStream))
    {
    string line;
    while ((line = await streamReader.ReadLineAsync()) != null)
    {
    var lineModifyLower = Regex
    .Replace(line, “[^а-яА-я \dictionary]”, “”)
    .ToLower();
    var words = lineModifyLower
    .Split(Separators, StringSplitOptions.RemoveEmptyEntries)
    .Where(ws => ws.Length >= 4);

    Parallel.ForEach(words, word =>
    {
    lock (lockObject)
    {
    if (wordCount.ContainsKey(word))
    {
    wordCount[word] = wordCount[word] + 1;
    }
    else
    {
    wordCount.Add(word, 1);
    }
    }
    });
    }
    }
    }
    return sorting[dic](wordCount).ToDictionary(k => k.Key, k => k.Value);
    }

    There’s so much to dislike about this code. Most of it is little stuff- it’s painfully nested, I don’t like methods which process file data also being the methods which manage file handles. Generics which look like this: Dictionary<ParamSortDic, Func<IDictionary<string, int>, IOrderedEnumerable<KeyValuePair<string, int>>>> are downright offensive.

    But all of that’s little stuff, in the broader context here. You’ll note that the file is read using ReadLineAsync, which is asynchronous. Of course, we await the results of that method in the same line we call it. await is a blocking operation, so… not asynchronous at all.

    Of course, that’s a trend with this block of code. Note that the words on each line are processed in a Parallel.ForEach. And the body of that ForEach starts by creating a lock, guaranteeing that only one thread is ever going to enter that block at the same time.

    Suffice to say, Aleksei didn’t recommend that candidate.

    [Advertisement]
    BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!

    Source: Read More 

    Hostinger
    Facebook Twitter Reddit Email Copy Link
    Previous ArticleBest Steam Deck and ROG Ally deals during Amazon Prime Day: Get gaming handhelds at a discount
    Next Article 10 Best Free and Open Source Audio Converters

    Related Posts

    Security

    Nmap 7.96 Launches with Lightning-Fast DNS and 612 Scripts

    May 15, 2025
    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-30419 – NI Circuit Design Suite SymbolEditor Out-of-Bounds Read Vulnerability

    May 15, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    VLC Developers Working on AI-Powered Real-Time Subtitles

    Linux

    Formula 1 Governing Body FIA Suffers Data Breach, Email Accounts Compromised

    Development

    CVE-2025-4135 – Netgear WG302v2 Command Injection Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    WazirX Cryptocurrency Exchange Loses $230 Million in Major Security Breach

    Development

    Highlights

    Development

    Critical Flaw in Microsoft Entra ID Allows Privileged Users to Gain Global Admin Status

    August 8, 2024

    A significant security flaw in Microsoft Entra ID identity and access management service has been…

    GenomeTools – genome analysis software

    February 24, 2025

    Resilience in the face of ransomware: A key to business survival

    April 10, 2025

    Data masking and performance improvements in AWS DMS 3.5.4

    April 30, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.