我有一个主表单,该表单有一个按钮,单击该按钮将显示带有进度条的复制窗口。我使用一个线程来完成复制工作,但是在完成复制后(文件复制正常并且复制窗口关闭)主窗体被冻结(窗体上的控件似乎不与之交互)。任务管理器显示没有太多工作 (0%)。这里有些奇怪。下面是复制对话的代码,请看:
public partial class FileCopier : Form
{
[DllImport("Kernel32")]
private extern static int CopyFileEx(string source, string destination, CopyProgressRoutine copyProgress, int data, ref int cancel, int flags);
private delegate int CopyProgressRoutine(long totalBytes, long bytesCopied, long streamSize, long streamCopied, int streamNumber, int callBackReason, int source, int destination, int data);
public FileCopier()
{
InitializeComponent();
}
#region private members
int cancel;
int copyFinished = -1;
#endregion
#region public methods
public void Copy(string source, string destination)
{
CoreHandling(source, destination);
}
public void MoveFile(string source, string destination)
{
CoreHandling(source, destination);
if (cancel == 0)//If there is no canceling action
{
//Delete the source file
File.Delete(source);
}
}
#endregion
#region private methods
private void CoreHandling(string source, string destination)
{
startTime = DateTime.Now;
ThreadStart ths = delegate
{
CopyFileEx(source, destination, UpdateCopyProgress, 0, ref cancel, 1);
};
new Thread(ths).Start();
ShowDialog();
while (copyFinished == -1)
{
Thread.Sleep(10);
}
copyFinished = -1;
}
private int UpdateCopyProgress(long totalBytes, long bytesCopied, long streamSize, long streamCopied, int streamNumber, int callBackReason, int source, int destination, int data)
{
if (InvokeRequired)
{
Invoke(new CopyProgressRoutine(UpdateCopyProgress), totalBytes, bytesCopied, streamSize, streamCopied, streamNumber, callBackReason, source, destination, data);
}
else
{
int percentage = (int)(((double)bytesCopied / totalBytes) * 100);
progressBar.Position = percentage;
Application.DoEvents();
if (totalBytes == bytesCopied || cancel == 1)
{
DialogResult = DialogResult.OK;
}
}
return 0;
}
#endregion
private void buttonCancel_Click(object sender, EventArgs e)
{
cancel = 1;
}
}
在我的主窗体的代码中,这里是 Button Click 事件处理程序:
private void buttonCopy_Click(object sender, EventArgs e){
using(FileCopier fileCopier = new FileCopier()){
fileCopier.Copy("My source file", "My destination file");
}
}
就是这样,复制完成后,上面的Copy()方法应该正常退出了。我不明白完成复制后还在做什么并使我的主要表格冻结。
您的帮助将不胜感激!