c#backgroundworker不能使用我想要的代码

bob*_*mac 2 c# copy button backgroundworker

我的代码在引人注目的时候没有出现任何错误,只是在试图运行时得到一个.它说ThreadStateException没有被我在多个地方搜索过的用户代码所取消,我的所有代码看起来都像我知道问题是什么一样.这是不起作用的代码

 private void button1_Click(object sender, EventArgs e)
 {
      backgroundWorker1.RunWorkerAsync();
 }

 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
 {
      FolderBrowserDialog dlg2 = new FolderBrowserDialog();
      if (dlg2.ShowDialog() == DialogResult.OK)
      //do whatever with dlg.SelectedPath
      {
           DirectoryInfo source = new DirectoryInfo(dlg.SelectedPath);
           DirectoryInfo target = new DirectoryInfo(dlg2.SelectedPath);

           DirectoryInfo dir = new DirectoryInfo(dlg.SelectedPath);
           FileInfo[] fis = dir.GetFiles("*", SearchOption.AllDirectories);
           foreach (FileInfo fi in fis)
           {
                if (fi.LastWriteTime.Date == DateTime.Today.Date)
                {
                    File.Copy(fi.FullName, target.FullName +"\\"+ fi.Name, true);
                }
           }

      }
 }
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激

Hen*_*man 8

您无法通过线程显示表单(对话框).

 private void button1_Click(object sender, EventArgs e)
 {
     using (FolderBrowserDialog dlg2 = new FolderBrowserDialog())
     {
       if (dlg2.ShowDialog() == DialogResult.OK)           
       {
          backgroundWorker1.RunWorkerAsync(dlg2SelectedPath);
       }
    }
 }


private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    string selectedpath = (string) e.Args;
    ....
}
Run Code Online (Sandbox Code Playgroud)

此外,请确保您处理Completed事件并检查if (e.Error != null) ...
否则您将忽略错误.