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

妖精的绣舞 提交于 2019-12-11 03:16:12

问题


I’m using the FileUtilities.CopyFile wrapper for CopyFileEx from here 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). And therefore asked this How do I get CopyFileEx to report back so I can cancel a file copy operation? 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. Why is that?


回答1:


You will need to call CopyFileEx from a background thread. At the moment the call to CopyFileEx is blocking the UI thread. That's why the UI does not update.

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:

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. Your message queue needs to be serviced regularly and so all long running tasks need to be run away from the UI thread.

One final point: remember that when you get your progress callback, you need to use Invoke or BeginInvoke when updating any UI. This is because code that updates UI needs to be run from the UI thread.



来源:https://stackoverflow.com/questions/8393336/why-is-fileutilities-copyfile-wrapper-for-copyfileex-interfering-with-winforms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!