【问题标题】:c# using BackgroundWorker while scan directores and its subfoldersc#在扫描目录及其子文件夹时使用BackgroundWorker
【发布时间】:2017-01-24 07:00:30
【问题描述】:

我在 c# 中有这个简单的代码,它可以找到所有目标目录及其子文件夹,但我在处理它时无法与我红色的 GUI 表单交互,我应该使用 BackgroundWorker 如何使用此代码实现:

  var dir = textBox1.Text = folderBrowserDialog1.SelectedPath; 
  textBox2.Text="";
  string[] extensions = { ".htm", ".html" };
  var files = Directory.EnumerateFiles(dir, "*.*",SearchOption.AllDirectories)
  .Where(s => s.EndsWith(".html") || s.EndsWith(".htm")).OrderBy(f => f);

                 foreach (string file in files)
                 { System.Diagnostics.Debug.WriteLine(file);
                   textBox2.AppendText(file+Environment.NewLine);
                 } 

【问题讨论】:

    标签: c# directory backgroundworker


    【解决方案1】:

    你读过这个链接吗?注意从其他线程更新 gui(使用 BackgroundWorker 这通常在 ProgressChanged 事件处理程序中完成:https://msdn.microsoft.com/en-us/library/3s8xdz5c(v=vs.110).aspx

    【讨论】:

    • 好吧,我试过没有工作循环不会工作一次然后它停止
    【解决方案2】:

    没关系,我找到了解决方案:

        void BackgroundWorker1DoWork(object sender, DoWorkEventArgs e)
        {  
              string[] extensions = { ".htm", ".html" };
              var files = Directory.EnumerateFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories)
             .Where(s => s.EndsWith(".html") || s.EndsWith(".htm")).OrderBy(f => f);
    
    
              foreach (string file in files)
               {  
                Thread.Sleep(5);
                System.Diagnostics.Debug.WriteLine(file);
                  backgroundWorker1.ReportProgress(0,file+Environment.NewLine);
               }
    
    
        }
        void BackgroundWorker1ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
    
          textBox2.AppendText(e.UserState as string);
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-28
      相关资源
      最近更新 更多