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

时间:2011-02-04 14:46:21

标签: c# button copy 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);
                }
           }

      }
 }

任何帮助将不胜感激

2 个答案:

答案 0 :(得分: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;
    ....
}

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

答案 1 :(得分:1)

在DoWork方法中添加一些异常处理。

请看这里:http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvcs/thread/74d91404-9bc8-4f8f-8eab-4265afbcb101/

string ErrorMessage = "";
void bgw_DoWork(object sender, DoWorkEventArgs ea)
{
    //some variable declarations and initialization
    try
    {
        //do some odbc querying
        ErrorMessage = "";
    }
    catch (Exception ex)
    {
        //stuff..
        ErrorMessage = ex.Message;
    }
}

void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Error != null || !string.IsNullOrEmpty(ErrorMessage))
    {
        //do something
        MessageBox.Show(ErrorMessage);
    }
    else
    {
        //do something else
    }
}