用c#和线程删除大量文件和子文件夹

发布于 2024-10-31 09:14:11 字数 60 浏览 1 评论 0原文

是否有人有示例或没有如何使用线程和 c# .net 删除文件夹中的大量文件和子目录。

谢谢

Does anybody have a sample or no how to delete a lot of files and sub directories in a folder with threads and c# .net.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

无可置疑 2024-11-07 09:14:11

最好的方法是调用 Directory.Delete(directory, true); ,这将删除目录、所有子目录和所有文件。无需穿线。

如果您想异步执行此操作(即让您的程序在目录删除发生时执行其他操作),请查看 异步调用同步方法

The best way is to call Directory.Delete(directory, true); That will delete the directory, all of the subdirectories, and all files. No threading required.

If you want to do it asynchronously (i.e. have your program do other things while the directory deletion is happening), then take a look at Calling Synchronous Methods Asynchronously.

眼泪都笑了 2024-11-07 09:14:11

执行类似的操作

ThreadPool.QueueUserWorkItem(delegate
{
    try
    {
         Directory.Delete(path, true);
    }
    catch { } //Do something 
});

Do something like this:

ThreadPool.QueueUserWorkItem(delegate
{
    try
    {
         Directory.Delete(path, true);
    }
    catch { } //Do something 
});
暖阳 2024-11-07 09:14:11

将其保留在操作系统上。它更清楚地知道如何安排操作,使其即使在繁重的工作负载下也能真正快速且良好地执行。如果程序的其余部分无法被阻止,只需从单独的线程分派它即可。

Leave it upon the operating system. It knows far better how to schedule the operations to make it really fast and well performing even under heady workload. In case the rest of your program can't be blocked, just dispatch it from a separate thread.

醉南桥 2024-11-07 09:14:11

如果您确实想尝试多线程(我想可能会有这样的情况,例如尝试获取不可用的网络资源,其中线程池将加快整体时间):

List<Task> tasks =
(from c in yourDirList select new Action(() =>
 {
  try
  {
   // do it
  }
  catch (Exception e)
  {
   // log it
  }
 })
 into action
 select Task.Factory.StartNew(action)).ToList();

tasks.ForEach(c => c.Wait());

If you do want to try multithreading it (I imagine that there might cases like trying to get at an unavailable network resource where a thread pool will speed up the overall time):

List<Task> tasks =
(from c in yourDirList select new Action(() =>
 {
  try
  {
   // do it
  }
  catch (Exception e)
  {
   // log it
  }
 })
 into action
 select Task.Factory.StartNew(action)).ToList();

tasks.ForEach(c => c.Wait());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文