首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WebClient DownloadFileAsync()块线程

WebClient DownloadFileAsync()块线程
EN

Stack Overflow用户
提问于 2013-05-31 21:11:28
回答 1查看 1.9K关注 0票数 3

我正在尝试使用WPF和MVVM从我的WPF服务器下载一个大文件(500 mb)。因此,以下属性都绑定到某种类型的控件(进度条)。问题是,即使在使用DownloadFileAsync时,应用程序仍然挂起。

从日志中可以看出,文件正在下载(当然,文件正在增长)。

这是我的密码:

代码语言:javascript
复制
    #region Methods

    private void StartDownload(string url, string localPath)
    {
        Logger.Debug("Starting to initialize file download");

        if (!_webClient.IsBusy)
        {
            _webClient = new WebClient();
            _webClient.Proxy = null; // http://stackoverflow.com/questions/754333/why-is-this-webrequest-code-slow/935728#935728
            _webClient.DownloadFileCompleted += webClient_DownloadFileCompleted;
            _webClient.DownloadProgressChanged += webClient_DownloadProgressChanged;

            _webClient.DownloadFileAsync(new Uri(url), localPath);
        }

        Logger.Debug("Finished initializing file download");
    }

    private void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
    {
        Logger.Debug("Download finished! Cancelled: {0}, Errors: {1} ", e.Cancelled, e.Error);
    }

    private void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        Logger.Debug("Downloading... Progress: {0} ({1} bytes / {2} bytes)", e.ProgressPercentage, e.BytesReceived, e.TotalBytesToReceive);

        if (!IsDownloadPaused)
        {
            DownloadFileProgress = e.ProgressPercentage;
            BytesReceived = e.BytesReceived;
            TotalBytesToReceive = e.TotalBytesToReceive;
        }
        else
        {
            Logger.Debug("Download paused...");
        }
    }

    #endregion Methods

根据评论请求编辑:它是一个.NET 4 CP应用程序,因此没有asyncawait。整个应用程序是无响应的,没有窗口大小,按钮点击或文本框交互。

当我闯入调试器时,我一直挂在OnPropertyChanged()-Method中(我认为这是因为大多数情况下都是这样),并得到以下调用堆栈:

代码语言:javascript
复制
Launcher.exe!Company.Product.Tools.Launcher.ViewModels.ViewModelBase.OnPropertyChanged(string propertyName) Line 16 + 0x59 bytes    C#
Launcher.exe!Company.Product.Tools.Launcher.ViewModels.DownloadViewViewModel.BytesReceived.set(long value) Line 82 + 0x21 bytes C#
Launcher.exe!Company.Product.Tools.Launcher.ViewModels.DownloadViewViewModel.webClient_DownloadProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e) Line 216 + 0x3f bytes  C#

它不会把挂在那里,,再往前走,就不会有任何延迟了。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-05-31 21:27:09

听起来你好像收到了很多关于下载字节数的反馈,而属性改变的事件处理程序相对来说效率很低。也许您应该限制更新BytesReceived的频率--按时间(例如,每秒更新5次)或增量(当更新超过K时更新)或某种混合版本。

不过,您可能还想了解属性中正在发生的事情--看看是否存在什么效率低下的问题,可以进行优化。

(第一步可能是只计算调用webClient_DownloadProgressChanged的次数。)

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16866059

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档