I Have this class to demonstrate my problem:
class Program
{
static List<FileInfo> _foundFiles;
static int _numberPadding = 0;
static Thread newThread;
static void Main(string[] args)
{
_foundFiles = new List<FileInfo>();
_shouldStop = false;
newThread = new Thread(new ThreadStart(StartSearch));
newThread.Start();
newThread.Join();
Console.WriteLine("Finished");
Console.ReadKey();
}
static volatile bool _shouldStop;
static void StartSearch()
{
IterateFileSystemNon(new DirectoryInfo(@"D:\OLD Melman\Music Backup\iTunes 28-06-11\Music"));
}
static void IterateFileSystemNon(DirectoryInfo folder)
{
string pad = CreatePadding();
Console.WriteLine("{0} Directory: {1}", pad, folder.Name);
foreach (var dir in folder.GetDirectories())
IterateFileSystemNon(dir);
pad = CreatePadding();
foreach (var file in folder.GetFiles())
{
if (file.Extension.Contains("mp3"))
{
_foundFiles.Add(file);
Console.WriteLine("{0} File: {1}", pad, file.Name);
}
}
_numberPadding = _numberPadding - 6;
}
static string CreatePadding()
{
_numberPadding = _numberPadding + 3;
var stringRepOfPadding = new StringBuilder(_numberPadding);
for (int i = 0; i < _numberPadding; i++)
{
stringRepOfPadding.Append(" ");
}
return stringRepOfPadding.ToString();
}
}
I have theses questions:
- This works in a console app, but this doesn’t work in a WindowsFormsApplication, it just goes straight to the
Joinstatement, why is this? - If the Join statement as Microsoft puts it “is suppose to block the current thread until the spawned thread has finished”. Surely this defeats the object of multi-threading? In my WindowsFormsApplication, I don’t want to block any thread while this thread is running it’s task.
- Why do I need the Join. Surely when my Iteration void has completed iterating then the thread should just terminate?!
- How inside the new thread do I indicate it has finished so that it will close the thread?
1 Answer