簡體   English   中英

downloader.DownloadFileTaskAsync 下載第一個文件后卡住

[英]downloader.DownloadFileTaskAsync stuck after downloading the first file

我正在使用下載

我的代碼是

    public DownloadWindow()
    {
        InitializeComponent();
        StartDownloading();
    }

    private async void StartDownloading()
    {
            var downloader = new DownloadService(downloadOpt);
            downloader.DownloadProgressChanged += OnDownloadProgressChanged;

            await downloader.DownloadFileTaskAsync(url1, file1);
            await downloader.DownloadFileTaskAsync(url2, file2);
    }

    private void OnDownloadProgressChanged(object sender, Downloader.DownloadProgressChangedEventArgs e)
    {
        try
        {
             this.Dispatcher.Invoke(new Action(() =>
            {

             downloadProgressBar.Value = e.ProgressPercentage;
            
            }));
        }
        catch { }
    }

第一個文件被下載並卡在第二個文件上。

如果我注釋掉第一個下載,第二個文件下載就好了。

創建另一個下載器 object 也無濟於事

我究竟做錯了什么?

根本原因是死鎖。 有兩種方法嘗試使用 Windows 消息隊列來訪問主 UI 線程,而彼此沒有機會繼續。

使用BeginInvoke()而不是Invoke()發布消息以避免將 UI 線程鎖定在 `OnDownloadProgressChanged.

像這樣:

private void OnDownloadProgressChanged(object sender, Downloader.DownloadProgressChangedEventArgs e)
{
           this.Dispatcher.BeginInvoke(new Action(() =>
          {
               downloadProgressBar.Value = e.ProgressPercentage;
          }));
}

StartDownloading()中的代碼也存在一些問題,例如對長時間運行的任務使用 fire 並忘記async void 人們會想要取消它或等到它完成。 此外,當對話框的 window 尚未完全構建時,它也不需要從構造函數中開始。


void StartDownloading()
{
   \\ Run download in a background thread 
   _downloadTask = Task.Run(()=>RunDownloading());
}

// Check the state of this task before closing the dialog.
Task _downloadTask;


async Task RunDownloading()
{
       var downloader = new DownloadService(downloadOpt);
       downloader.DownloadProgressChanged += OnDownloadProgressChanged;

       await downloader.DownloadFileTaskAsync(url1, file1);
       await downloader.DownloadFileTaskAsync(url2, file2);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM