调用控制-复制文件阻止了另一个线程

时间:2018-06-28 12:29:25

标签: c# task invoke

我的背景工作人员有问题。我编写了将文件从本地磁盘复制到网络磁盘的程序,我想显示进程运行时进度条旋转成圆圈(不显示进度)。当我将backgroundworker设置为空按钮时,一切正常,但是当我将backgroundworker设置为按钮时,复制功能完成时,具有处理文件进度条的功能。为什么以及如何解决?下面的代码。

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
circularProgressBar1.BeginInvoke(new MethodInvoker(sd));
}

public void sd()
{
    circularProgressBar1.Visible = true;
   circularProgressBar1.Enabled = true;
   circularProgressBar1.Style = ProgressBarStyle.Marquee;
}
private void backgroundWorker1_ProgressChanged(object sender, 
ProgressChangedEventArgs e)
{
    circularProgressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, 
RunWorkerCompletedEventArgs e)
{
    MessageBox.Show("End");
}

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

private void copy_Click(object sender, EventArgs e)
{
 backgroundWorker1.RunWorkerAsync();
   List<string> pathList = new List<string>();

// for example add 1000 path
pathList.add("C:\test\2.jpg");
pathList.add("C:\test\3.jpg");

foreach(string in in pathList)
{
    File.Copy(in,"D:\test2",true);
}   
}

1 个答案:

答案 0 :(得分:1)

您需要将File.Copy放在backgroundWorker1_DoWork中-这是完成后台工作的地方。

您可以在调用circularProgressBar之前激活backgroundWorker1.RunWorkerAsync,并在backgroundWorker1_RunWorkerCompleted中将其禁用。