为什么 CopyFileEx 的 FileUtilities.CopyFile 包装器会干扰 winforms? [英] Why is FileUtilities.CopyFile wrapper for CopyFileEx interfering with winforms?

查看:27
本文介绍了为什么 CopyFileEx 的 FileUtilities.CopyFile 包装器会干扰 winforms?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 FileUtilities.CopyFile 包装器用于 CopyFileEx 从这里 http://msdn.microsoft.com/en-us/magazine/cc163851.aspx.我认为 CopyFileCallbackAction 直到文件被复制后才会被调用(我试过复制一个大文件).因此问这个 如何让 CopyFileEx 返回报告以便我可以取消文件复制操作? 问题.但是现在我发现它实际上被调用了很多次,但由于某种原因,它弄乱了我试图显示进度的表单——表单在复制完成之前不会更新.事实上,如果我尝试在 Shown 事件处理程序中运行它 - 表单有空框,按钮应该在那里 - 直到复制完成.这是为什么?

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?

推荐答案

您需要从后台线程调用 CopyFileEx.目前对 CopyFileEx 的调用正在阻塞 UI 线程.这就是 UI 不更新的原因.

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.

需要说明的是,这就是调用 CopyFileEx 时发生的情况:

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

在文件复制的整个过程中,执行线程忙于复制文件而不是泵送消息队列.尽管这是 WinForms 而不是 Win32,但 WinForms 是围绕标准 Win32 GUI 框架的相对轻量级的包装器.您的消息队列需要定期提供服务,因此所有长时间运行的任务都需要远离 UI 线程.

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.

最后一点:请记住,当您获得进度回调时,您需要在更新任何 UI 时使用 InvokeBeginInvoke.这是因为更新 UI 的代码需要从 UI 线程运行.

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.

这篇关于为什么 CopyFileEx 的 FileUtilities.CopyFile 包装器会干扰 winforms?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆