我在C#中创建一个Windows服务,它检查旧文件并定期从指定目录中删除它们。我尝试使用Threadpooling和Task并行库来实现这一点。我试图通过不使用锁和重置事件使其异步,但这对我来说没有用,因为它正在跳过一些操作。我的目标是使用所有核心来处理此任务。由于我正在进行I / O操作(文件删除),哪一个会更好?如果效率很高,还要提出其他建议。
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();
}
}
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);
}
}
});