Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

button - c# backgroundworker won't work with the code I want it to do

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

      }
 }

any help will be appreciated

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...