简体   繁体   English

为什么CopyFileEx的FileUtilities.CopyFile包装器会干扰winforms?

[英]Why is FileUtilities.CopyFile wrapper for CopyFileEx interfering with winforms?

I'm using the FileUtilities.CopyFile wrapper for CopyFileEx from here http://msdn.microsoft.com/en-us/magazine/cc163851.aspx . 我从这里使用FileUtilities.CopyFile包装CopyFileEx http://msdn.microsoft.com/en-us/magazine/cc163851.aspx I thought the CopyFileCallbackAction doesn't get called until after the file is copied (I've tried copying a large file). 我认为CopyFileCallbackAction在复制文件之后才会被调用(我试过复制一个大文件)。 And therefore asked this How do I get CopyFileEx to report back so I can cancel a file copy operation? 因此问这个如何让CopyFileEx报告回来这样我可以取消文件复制操作? question. 题。 But now I've found that it actually gets called many times, but for some reason it messes the form on which I'm trying to show the progress – the form doesn't get updated until the copy is done. 但现在我发现它实际上被多次调用,但由于某种原因它混淆了我试图显示进度的形式 - 在复制完成之前,表单不会更新。 In fact, if I try running it in the Shown event handler – the form has empty boxes where buttons are supposed to be – until the copy is done. 事实上,如果我尝试在Shown事件处理程序中运行它 - 表单有空白框,其中按钮应该是 - 直到复制完成。 Why is that? 这是为什么?

You will need to call CopyFileEx from a background thread. 您需要从后台线程调用CopyFileEx At the moment the call to CopyFileEx is blocking the UI thread. 目前,对CopyFileEx的调用阻止了UI线程。 That's why the UI does not update. 这就是UI不更新的原因。

The callback action is indeed called repeatedly. 回调操作确实是重复调用的。 This is so that you can report to the user the progress of a long running file operation. 这样您就可以向用户报告长时间运行的文件操作的进度。

Just to be clear, this is what happens when you call CopyFileEx : 为了清楚CopyFileEx ,这就是调用CopyFileEx时会发生的情况:

Enter CopyFileEx
  Start copying
  Call your callback
  Continue copying
  Call your callback
  ....
Return from CopyFileEx

For the entire duration of the file copy, the executing thread is busy copying the file rather than pumping the message queue. 对于文件复制的整个持续时间,执行线程正在忙于复制文件而不是抽取消息队列。 Although this is WinForms and not Win32, WinForms is a relatively lightweight wrapper around the standard Win32 GUI framework. 虽然这是WinForms而不是Win32,但WinForms是围绕标准Win32 GUI框架的相对轻量级的包装器。 Your message queue needs to be serviced regularly and so all long running tasks need to be run away from the UI thread. 您的消息队列需要定期维护,因此所有长时间运行的任务都需要从UI线程中运行。

One final point: remember that when you get your progress callback, you need to use Invoke or BeginInvoke when updating any UI. 最后一点:请记住,当您获得进度回调时,您需要在更新任何UI时使用InvokeBeginInvoke This is because code that updates UI needs to be run from the UI thread. 这是因为需要从UI线程运行更新UI的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM