Question

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.

Was it helpful?

Solution

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
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top