Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6763233
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T14:27:06+00:00 2026-05-26T14:27:06+00:00

In F# I could use // Synchronous version let rec folderCollectorSync path = try

  • 0

In F# I could use

// Synchronous version
let rec folderCollectorSync path =
    try
        let dirs = Directory.GetDirectories path 
        for z in dirs do folderCollectorSync z
    with
    | ex -> ()

// Asynchronous version that uses synchronous when 'nesting <= 0'
let rec folderCollector path nesting =
    async { if nesting <= 0 then return folderCollectorSync path 
            else 
                try
                    let dirs = Directory.GetDirectories path 
                    do! [for z in dirs -> folderCollector z (nesting - 1) ] 
                        |> Async.Parallel |> Async.Ignore
                with ex -> () }

folderCollector @"C:\" 5 |> Async.RunSynchronously

to travel a directory async for the first 5 levels.

I’ve tried to redo the code above (without the use of Async.Parallel of course).

And it looks something like:

static void TravelSync(string path, CountdownEvent cd)
{
    var dirs = Directory.GetDirectories(path);
    var cdown = new CountdownEvent(dirs.Length);

    foreach (var d in dirs)
        TravelSync(d, cdown);
    cdown.Wait();
    cd.Signal();
}

static void Travel(string path, int nesting, CountdownEvent cd)
{
    if (!Directories.Contains(path))
    {
        if (nesting <= 0)
        {
            TravelSync(path, cd);
        }
        else
        {
            Messages.Add(path);
            Directories.Add(path);

            var dirs = Directory.GetDirectories(path);
            var cdown = new CountdownEvent(dirs.Length);

            foreach (var d in dirs)
                ThreadPool.QueueUserWorkItem(o => Travel(d, nesting - 1, cdown));

            cdown.Wait();
            cd.Signal();
        }
    }
}

By no surprise the c# version is slow as hell, and also it just stops after have crawled 5 directories.

So my question is: How can F# keep track of the async operations? My C# version is poor, and have lots of perfomance problems.

I’m aware of that I simply can use the F# code in my C# project, but since this is just for exercise I’m more interested in how to do it in C#.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T14:27:06+00:00Added an answer on May 26, 2026 at 2:27 pm

    Firstly, there is a bug in Travel(), where you queue the thread pool work for each directory. You are capturing d in the lambda, but by the time the lambda runs, d will probably always be the last path in the dirs collection. Here’s the fix for that:

    foreach ( var d in dirs )
    {
        var d2 = d;
        ThreadPool.QueueUserWorkItem( o => Travel( d2, nesting - 1, cdown ) );
    }
    

    Apart from that, you are creating a CountdownEvent for every directory on your disk, which is quite expensive. In fact, the CountdownEvent in TravelSync is redundant as this runs synchronously. You can just get rid of them:

    static void TravelSync(string path, CountdownEvent cd)
    {
        var dirs = Directory.GetDirectories(path);
        //var cdown = new CountdownEvent(dirs.Length);
    
        // this is normal synchronous code
        foreach (var d in dirs)
            TravelSync(d, null);
    
        //cdown.Wait();
        if ( cd != null ) cd.Signal();
    }
    

    If you’re using .NET 4.0, you can clean up Travel() as well, using Tasks:

    ...
    else
    {
        Messages.Add( path );
        Directories.Add( path );
    
        try
        {
            var dirs = Directory.GetDirectories( path );
    
            var tasks = dirs.Select(
                d => Task.Factory.StartNew(
                    () => Travel( d, nesting - 1, null )
                )
            ).ToArray();
    
            Task.WaitAll( tasks );
    
            foreach ( var t in tasks ) t.Dispose();
        }
        catch ( Exception x )
        {
            ...
        }
    }
    

    Of course, the Messages and Directories collections must be thread safe.


    EDIT: Actually, PLINQ makes this even easier:

        Parallel.ForEach( dirs, d => Travel( d, nesting - 1, null ) );
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is there an asynchronous version of DirectoryInfo.GetFiles / Directory.GetDirectories in dotNet? I'd like to
I could use some help creating an XSL template that will take a string
could someone help me with the regex pattern that i could use to match
I could use some help writing a regular expression. In my Django application, users
I could use the following: <fileset dir=C:\Program Files\eclipse\plugins\myplugin> <include name=extraStuff.jar /> </fileset> But that
Common question but I could use an english explanation. Is it like Java where
It seems like you could use a mashup of Relector and a Debugger to
With C# 3.0 you could use many of its features (object initializers, var variables,
I am getting the following error and could use some help resolving it. Anyone
We're having a small issue and could use some help - we have the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.