title: Process List of Files Asynchronously using async and await in C# Console App
body: <p>I'm playing around with <code>async</code> and <code>await</code> in C# in a simple little console application. My goal is simple: To process a list of files in asynchronous manner, so that the processing of one file does not block the processing of others. None of the files are dependent on one-another, and there are (let's say) thousands of files to go through.</p>
  
  <p>Here's is the code I have currently.</p>
  
  <pre><code>public class MyClass
  {
      public void Go()
      {
          string[] fileSystemEntries = Directory.GetFileSystemEntries(@"Path\To\Files");
  
          Console.WriteLine("Starting to read from files!");
          foreach (var filePath in fileSystemEntries.OrderBy(s =&gt; s))
          {
              Task task = new Task(() =&gt; DoStuff(filePath));
              task.Start();
              task.Wait();
          }
      }
  
      private async void DoStuff(string filePath)
      {
          await Task.Run(() =&gt;
          {
              Thread.Sleep(1000);
              string fileName = Path.GetFileName(filePath);
              string firstLineOfFile = File.ReadLines(filePath).First();
              Console.WriteLine("{0}: {1}", fileName, firstLineOfFile);
          });
      }
  }
  </code></pre>
  
  <p>And my <code>Main()</code> method simply invokes this class:</p>
  
  <pre><code>public static class Program
  {
      public static void Main()
      {
          var myClass = new MyClass();
          myClass.Go();
      }
  }
  </code></pre>
  
  <p>There's some piece to this asynchronous programming patten that I seem to be missing, though, since whenever I run the program, it seems random how many files are actually processed, anywhere from none of them to all six of them (in my example file set). </p>
  
  <p>Basically, the main thread isn't waiting for all of the files to be processed, which I suppose is part of the point of asynchronously-running things, but I don't quite want that. All I want is: Process as many of these files in as many threads as you can, but still wait for them all to complete processing before finishing up.</p>