c# backgroundworker 不能使用我想要的代码 [英] c# backgroundworker won't work with the code I want it to do

查看:22
本文介绍了c# backgroundworker 不能使用我想要的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码在强制执行时不会出现错误,我只是在尝试运行它时得到一个.它说 ThreadStateException 没有被我在多个地方搜索过的用户代码处理,我所有的代码看起来都以同样的方式工作,我知道问题出在哪里.这是不工作的代码

my code brings up no errors when compelling i just get one while trying to run it. it says ThreadStateException was unhanded by the user code i have searched for this in multiple places and all my code looks to work in the same way i have know idea what the problem is. here is the code that isnt working

 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);
                }
           }

      }
 }

任何帮助将不胜感激

推荐答案

你不能通过线程显示表单(对话框).

You cannot show a Form (Dialog) from withing the Thread.

 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;
    ....
}

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

Also, make sure you handle the Completed event and check if (e.Error != null) ...
Otherwise you will be ignoring errors.

这篇关于c# backgroundworker 不能使用我想要的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆