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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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);
    }
}
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):

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

But you would need:

1
using System.Threading.Tasks;
using System.Threading.Tasks;

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
195 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

Leave a Reply