C# Example – Using Parallel ForEach to Improve Existing Code


C# 4.0 or above provides the Parallel.For and Parallel.ForEach to support parallelism in an intuitive manner. In this post, a function is coded to delete trash files older than 7 days. And the core part is:

private static void DeleteOldRpmCache(int daysAgo = 7)
{
    var tempDir = Path.GetTempPath();
    var caches = Directory.GetFiles(tempDir, "*.tmp", SearchOption.TopDirectoryOnly);
    if (caches.Length <= 0) return;
    var oldCaches = caches.Where(c =>
    {
        var ts = DateTime.Now - File.GetLastAccessTime(c);
        return ts.Days > daysAgo;
    }).ToArray();
    foreach (var t in oldCaches.Where(File.Exists))
    {
        File.Delete(t);
    }
}

And you could just rewrite the last foreach to task executing in parallel (multithreading):

Parallel.ForEach(oldCaches.Where(File.Exists), File.Delete);

But you would need:

using System.Threading.Tasks;

–EOF (The Ultimate Computing & Technology Blog) —

178 words
Last Post: Regex Coding Exercise - Valid Phone Numbers
Next Post: How to Add a Share Dropdown Menu after Each Post? (Javascript)

The Permanent URL is: C# Example – Using Parallel ForEach to Improve Existing Code (AMP Version)

Leave a Reply