将所有文件记录在一个大目录中

发布于 2024-07-11 14:34:34 字数 542 浏览 4 评论 0原文

我有许多目录,其中包含大量文件(约 10,000 个)。 我想在我的应用程序中创建这些文件的列表,并且已经对 io 访问进行了线程化,以便应用程序在加载时不会冻结。 但是,如果我在加载所有文件之前退出应用程序,则线程不会响应 .Join(),直到完成对 dirInfo.GetFiles(...) 的调用:

// ... mythread
    DirectoryInfo dirInfo = new DirectoryInfo(path);
    foreach(FileINfo file in dirInfo.GetFiles(extension)) 
    {
        // with large directories, the GetFiles call above 
        //    can stall for a long time
        ...

将文件缓存到 foreach 之外只会解决问题。 我需要某种线程式回调方式来查找目录中的文件,但我不知道该怎么做。 任何帮助,将不胜感激。

非常感谢, 坦普恩。

I've got a number of directories with a large number of files in them (~10,000). I want to create a list of these files in my app, and have already threaded the io access so that the app doesn't freeze while they load. However if I exit the app before all files are loaded, the thread doesn't respond to the .Join() until the call to dirInfo.GetFiles(...) is completed:

// ... mythread
    DirectoryInfo dirInfo = new DirectoryInfo(path);
    foreach(FileINfo file in dirInfo.GetFiles(extension)) 
    {
        // with large directories, the GetFiles call above 
        //    can stall for a long time
        ...

Caching the files out of the foreach just moves the problem. I need some kind of threaded, callback-y way of finding the files in the directory and I'm not sure how to do that. Any help would be appreciated.

Many thanks,
tenpn.

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

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

发布评论

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

评论(2

情魔剑神 2024-07-18 14:34:34

您应该使用 ThreadPool 类中的线程。 这将使其成为后台线程,并且当应用程序关闭时它应该收到 ThreadInteruptException。

You should use a Thread from the ThreadPool class. This will make it a background thread and it should receive a ThreadInteruptException when the application closes.

月寒剑心 2024-07-18 14:34:34

当您的应用程序即将执行时,您可以调用 Thread.Abort()关闭(在加入之前)。

myThread.Abort();
// Wait for myThread to end.
myThread.Join();

另外,您可能希望在线程方法中捕获 ThreadAbortException 并在必要时进行一些终结/清理。

try {
    DirectoryInfo dirInfo = new DirectoryInfo(path);
    foreach(FileINfo file in dirInfo.GetFiles(extension)) 
    {
        // with large directories, the GetFiles call above 
        //    can stall for a long time
        ...
    }
}
catch (ThreadAbortException e)
{
    // cleaning
}

You can call Thread.Abort() when your application is about to close (before the Join).

myThread.Abort();
// Wait for myThread to end.
myThread.Join();

Also, you might want to catch the ThreadAbortException in the thread method and do some finalization/cleaning, if necessary.

try {
    DirectoryInfo dirInfo = new DirectoryInfo(path);
    foreach(FileINfo file in dirInfo.GetFiles(extension)) 
    {
        // with large directories, the GetFiles call above 
        //    can stall for a long time
        ...
    }
}
catch (ThreadAbortException e)
{
    // cleaning
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文