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

C# 调用控制-复制文件阻止另一个线程,c#,task,invoke,C#,Task,Invoke,我和后台工作人员有问题。我编写了将文件从本地磁盘复制到网络磁盘的程序,我想在进程运行时显示progressbar旋转(不显示进度)。当我将backgroundworker设置为空按钮时,一切正常,但当我将backgroundworker设置到按钮中,该按钮具有复制文件的功能,复制过程完成时,进度条会显示出来。我为什么以及如何解决这个问题?下面是代码 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {

我和后台工作人员有问题。我编写了将文件从本地磁盘复制到网络磁盘的程序,我想在进程运行时显示progressbar旋转(不显示进度)。当我将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);
}   
}
private void backgroundWorker1\u DoWork(对象发送方,DoWorkEventArgs e)
{
circularProgressBar1.BeginInvoke(新方法调用程序(sd));
}
公共图书馆
{
circularProgressBar1.Visible=true;
circularProgressBar1.Enabled=true;
circularProgressBar1.Style=ProgressBarStyle.Marquee;
}
私有void backgroundWorker1\u ProgressChanged(对象发送方,
ProgressChangedEventArgs(e)
{
circularProgressBar1.Value=e.ProgressPercentage;
}
私有void backgroundWorker1\u RunWorkerCompleted(对象发送方,
RunWorkerCompletedEventArgs(e)
{
MessageBox.Show(“结束”);
}
私有无效按钮1\u单击\u 1(对象发送者,事件参数e)
{
backgroundWorker1.RunWorkerAsync();
}
私有无效复制\u单击(对象发送者,事件参数e)
{
backgroundWorker1.RunWorkerAsync();
列表路径列表=新列表();
//例如,添加1000路径
添加(“C:\test\2.jpg”);
添加(“C:\test\3.jpg”);
foreach(路径列表中的字符串)
{
Copy(在“D:\test2”中为true);
}   
}

您需要将
文件复制到
backgroundWorker1\u DoWork
中-这是后台工作的完成位置


在调用
backgroundWorker1.RunWorkerAsync
之前,您可以激活
circularProgressBar
,并在我放入文件时在
backgroundWorker1\u RunWorkerCompleted

中禁用它。复制到backgroundWorker1\u doWork它不工作,因为我遇到错误:“进程无法访问该文件,因为其他进程正在使用该文件“或者我应该何时激活circularProgressBar?当用户点击按钮时不会?您不能在UI线程中保持文件打开。删除文件。从复制中的原始位置复制。单击。首先,尝试不使用circularProgressBar。然后在启动复制线程之前激活它,复制完成后立即禁用。根据您的程序逻辑,这可能分别是复制单击或运行工作完成。