I am creating a windows service in C# which checks for older files and deletes them periodically from a specified directory. I tried to achieve this with Threadpooling and Task parallel library. I tried to make it async by not using locks and reset events but that did not work out for me as it was skipping some operations in between. My aim is to use all cores to process this task. Since I am doing I/O operation (file delete) which one would be better out of these two? Also suggest something else if it is efficient.
Threadpool code:
foreach (string file in files)
{
using (AutoResetEvent signal = new AutoResetEvent(false))
{
ThreadPool.QueueUserWorkItem(delegate (object o)
{
if (File.GetLastWriteTime(file) <= DateTime.Today.AddDays(MaintainDuration))
{
File.Delete(file);
TestSuccessLog(file + " is deleted from thread " + Thread.CurrentThread.ManagedThreadId);
}
signal.Set();
});
signal.WaitOne();
}
}
TPL code:
object sync = new Object();
Parallel.ForEach(files, file =>
{
lock (sync)
{
if (File.GetLastWriteTime(file) <= DateTime.Today.AddDays(MaintainDuration))
{
File.Delete(file);
TestSuccessLog(file + " is deleted from thread " + Thread.CurrentThread.ManagedThreadId);
}
}
});