线程已退出代码0但尚未完成它的工作

时间:2014-05-06 09:02:47

标签: c# multithreading

我对C#中的多线程有点新意,并想知道为什么会发生这种情况:

我有线程1以异步方式加载文件。线程2用于始终检查线程是否仍在运行,如果线程1停止运行,它应该更新UI。

现在,我知道有更好的方法来实现我想要的任务或其他机制,但是一旦我遇到这个问题,我需要先了解使用此实现的错误,然后再学习更好的方法。

问题在于,有时它执行得非常好,而在其他时候线程只是退出代码0而不更新我的UI以通知它已完成工作。

实际代码:

 // Call File Manager (singleton) Async file loader method from the MainWindow.cs class
    fm.loadFromDirAsync(new DirectoryInfo(dialog.SelectedPath));


 // This method is in the File Manager singleton class
public void loadFromDirAsync(DirectoryInfo di)
{
    loadFiles = new Thread(() => FullDirList(di, "*.mp3"));
    loadFiles.Start();
    loadFiles.Name = "loadFromDirAsync";

}

// Back to MainWindow class, start a new thread to check if the async load thread 
   is still running:

          // Check if finished loading
    Thread t = new Thread(() => load());
    t.Start();
    t.Name = "LoaderThread";


// this method (in MainWindow class) checks if the loader thread in File Manager is still alive:
           private void load()
{
    while (runCheck)
    {

        // If Async file loading thread finished...
        if (!fm.isThreadStillLoading())
        {
            Console.WriteLine("Done running");

            Dispatcher.Invoke(
              System.Windows.Threading.DispatcherPriority.Normal,
             new Action(
        delegate()
        {
            loadBTN.IsEnabled = true;
            pb.IsIndeterminate = false;
            pb.IsEnabled = false;
            runCheck = false;
            pbLabel.Content = string.Format("Finished Indexing {0} files in {1} folder - Ready to play.", fm.filesCount, fm.foldersCount);

        }
         ));

        }
    }
}

0 个答案:

没有答案