I'm playing around with async
and await
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.
Here's is the code I have currently.
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 => s))
{
Task task = new Task(() => DoStuff(filePath));
task.Start();
task.Wait();
}
}
private async void DoStuff(string filePath)
{
await Task.Run(() =>
{
Thread.Sleep(1000);
string fileName = Path.GetFileName(filePath);
string firstLineOfFile = File.ReadLines(filePath).First();
Console.WriteLine("{0}: {1}", fileName, firstLineOfFile);
});
}
}
And my Main()
method simply invokes this class:
public static class Program
{
public static void Main()
{
var myClass = new MyClass();
myClass.Go();
}
}
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).
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.