简体   繁体   English

当我们使用DownloadFileAsync时如何阻止主线程

[英]How to Block main Thread when we use DownloadFileAsync

In my project I have a section to Download File . 在我的项目中,我有一节下载文件。 I use DownloadFileAsync() Method to Download and Add Two Event Handler : 我使用DownloadFileAsync()方法下载并添加两个事件处理程序:

  • DownloadProgressChanged 下载进度更改

  • DownloadFileCompleted 下载文件已完成

I want when Use DownloadFileAsync to Download File ,Block main thread , because i don't want users can click on the button before download completed. 我想要使​​用DownloadFileAsync来下载File时,阻止主线程,因为我不希望用户可以在下载完成之前单击按钮。

Part of my code: 我的部分代码:

WebClient webClient = new WebClient();
        webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChange);
        webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
        Uri Url = new Uri(txtUrl.Text.Trim());
        webClient.DownloadFileAsync(Url,FolderDialog.SelectedPath+System.IO.Path.GetFileName(txtUrl.Text) );

How can I do this ? 我怎样才能做到这一点 ? I searched on the internet but I can't found useful Result. 我在互联网上搜索,但找不到有用的结果。 thanks 谢谢

It's better to disable controls than to deliberately block the UI thread. 最好禁用控件而不是故意阻止UI线程。 In Windows Forms, this can be done by setting Control.Enabled to false . 在Windows窗体中,可以通过将Control.Enabled设置为false来完成。 I'm not familiar with WPF so can't say what you'd do there. 我对WPF不熟悉,所以无法说出您要在那里做些什么。 Anyway, disabling controls gets you the behavior you desire without stopping the normal processing of events, so the user can still move the window, it'll still repaint, etc. 无论如何,禁用控件可以使您获得所需的行为,而无需停止事件的正常处理,因此用户仍然可以移动窗口,仍然重新绘制窗口等。

You don't really need to disable the whole thread, just disable the button. 您实际上不需要禁用整个线程,只需禁用按钮即可。 If you really want to disable the main thread just call the thread.sleep but that defeats the purpose of downloading async as the end result is the same as downloading normally. 如果您确实要禁用主线程,则只需调用thread.sleep,但这会破坏下载异步的目的,因为最终结果与正常下载相同。

As others have said, in my experience the general way of doing this is: 正如其他人所说,以我的经验,这样做的一般方式是:

  1. Button is disabled before doing any downloading. 在进行任何下载之前,按钮被禁用。
  2. Download begins. 开始下载。
  3. Download completion event handler enables the button again. 下载完成事件处理程序再次启用该按钮。
  4. Additionally, in the event of a problem the button should be enabled. 此外,如果出现问题,应启用该按钮。

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

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