因此,在下面的片段中,我只需查看特定文件夹并将图像从源复制到目的地。
副本非常快,它适用于第一批文件夹(可能是20个左右),需要几秒钟。但随后进度条停止移动,我得到一个旋转的鼠标光标。我可以查看目标文件夹,它仍在处理文件夹。
完成后,我会看到“Process Complete”对话框,进度条为100%,一切运行正常。
只是想确保最终用户认为它没有被冻结。
private void readInvoices()
{
string InvoiceFile = txtInvoiceFile.Text;
//read in the text file and get all the invoices to copy
string[] Invoices = File.ReadAllLines(InvoiceFile);
//set the max val of the progress bar
progBar.Maximum = Invoices.Length;
try
{
//for every invoice
foreach (string invoice in Invoices)
{
//Set the source and destination directories
string sourceInvFolder = string.Format(@"{0}\{1}", txtSource.Text, invoice);
string destInvFolder = string.Format(@"{0}\{1}", txtDest.Text, invoice);
DirectoryInfo SourceDI = new DirectoryInfo(sourceInvFolder);
DirectoryInfo DestDI = new DirectoryInfo(destInvFolder);
//we know we have it in the CSV but does the directory actually exist?
//if so then let's process
if (Directory.Exists(SourceDI.FullName) == true)
{
//let's copy of the files
CopyAll(SourceDI, DestDI);
RenameFolder(sourceInvFolder);
}
//inc the progress bar
progBar.Increment(1);
}
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex.Message);
}
finally
{
MessageBox.Show("Process Complete");
CleanUp();
}
}
答案 0 :(得分:1)
如果你想要Just want to make sure the end user doesn't think it's frozen.
,你应该使用多线程。适合此任务的更合适的类是BackgroundWorker
来自MSDN:
BackgroundWorker类允许您在单独的专用线程上运行操作。下载和数据库事务等耗时的操作可能会导致用户界面(UI)在运行时停止响应。当您需要响应式UI并且您遇到与此类操作相关的长时间延迟时,BackgroundWorker类提供了一种方便的解决方案。
尝试按照msdn提供的示例,将您方法的调用readInvoices()
放入DoWork
事件
答案 1 :(得分:0)
你的代码在UI线程上运行(至少我假设你在catch块中有一个MessageBox)。
因此,它不一定会处理UI更新。
使用TPL查看工作。
http://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx
答案 2 :(得分:0)
UI冻结,因为它在单个线程中运行。修复冻结部分的解决方法是将这行代码放在循环中。
Application.DoEvents();
此代码检查是否有等待处理的消息,如果有,则在继续进行另一个循环之前处理它们。您可以使用ProgressBar控件让用户查看已处理的内容。如果您不想继续使用单线程方法,请使用BackGroundWorker来防止表单显示为冻结。这是多线程,这意味着当你做其他事情时,一个单独的线程正在处理某些东西。
有一件事要记住,使用上面的代码会使整个循环过程变慢,因为它必须检查每个循环,这意味着更多的工作,作为回报,您将获得实时进度报告。它看起来被冻结的原因是循环还没有完成,你必须先让它先完成,然后才能做其他事情,因为它在一个线程中运行。