c# - WebClient.DownloadProgressChanged 不触发

标签 c# .net download webclient

使用 C# 在 Visual Studio 中进行一些编程,我正在尝试下载文件并将进度链接到 ProgressBar。当我在 Visual Basic 中执行此操作时,它工作得非常好,但当我尝试在 C# 中执行此操作时,Client.DownloadProgressChanged 事件不会触发。

System.Net.WebClient Client = new System.Net.WebClient();
Client.DownloadProgressChanged += Client_DownloadProgressChanged;
Client.DownloadFileAsync(new Uri(url), filepath + filename);
while (Client.IsBusy) { }

Client_DownloadProgressChanged 中唯一的内容是一些将 TextBox 的值更改为“Test1”的代码,我这样做只是为了看看它是否运行。

最佳答案

这个:

while (Client.IsBusy) { }

绑定(bind) UI 消息循环。它保持它的消耗并且不允许处理任何其他消息。同时,事件正在 UI 线程上排队,该线程被阻塞。

如果您评论该行并且下载完成,您将看到文本框正确更新。

你应该重新考虑你想要做什么。如果是客户端,请考虑将 while 循环移至 background thread

关于c# - WebClient.DownloadProgressChanged 不触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28463861/

相关文章:

c# - 我的日志管理器的路径共享违规

c# - 如何在程序退出前运行代码?

.net - DNX 1.0.0-RC1-Update2 中有什么

.net - 通过多台机器对数据进行时间戳记 - 时间不对?

angularjs - 使用 AngularJS 从服务器下载并保存文件

c# - 读取嵌套的动态 JSON 属性

c# - 在 C# 中将列表列表作为类使用

c# - 采用 IDisposable 模式

ASP.NET 文件下载 - 检测用户是否取消下载?

android - 如何向 Google Play 请求下载统计信息