我有这堂课来证明我的问题:
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();
}
}
我有这些问题:
-
这适用于控制台应用程序,但这在WindowsFormsApplication中不起作用,它直接进入
Join
语句,为什么会这样? -
如果Microsoft声明的连接语句为"is suppose to block the current thread until the spawned thread has finished" . 当然这会打败多线程的对象?在我的WindowsFormsApplication中,我没有't want to block any thread while this thread is running it'的任务 .
-
为什么我需要加入 . 当我的Iteration void迭代完成后,线程应该终止?!
-
新线程内部如何表明它已完成,以便关闭线程?
2 回答
使用Join,您将挂起UI线程 . 使用BackgroundWorker组件在后台线程中搜索文件 .
不要启动线程并加入它 . 这与在一个线程中按顺序执行所有工作相同,因为在这种情况下不会异步执行任何操作 .
您不需要加入(参见第2页) . 在UI线程中使用Join总是坏主意 .
您不需要指示线程已完成以关闭线程 . 当线程委托完成执行时,线程将退出 . 见Multithreading: Terminating Threads
"Goes straight to the Join"是什么意思?它's perfectly possible that a the initiating thread will hit the Join before the other thread even gets scheduled and hits a breakpoint. Can you elaborate on what the Windows Forms app is doing that isn' t你期望什么?也许在这种情况下会导致工作线程过早退出?
您无需立即致电加入 . 这个想法是你启动线程,在当前线程上做任何你想做的事情,当你需要第二个线程的结果时,你调用Join来等待它完成 .
是的,线程将在枚举完成时结束 .
您只需要从传递给
Thread
构造函数的方法返回 . (StartSearch
在你的情况下) .