【问题标题】:Application Dispatcher doesn't update and doesn't give errorsApplication Dispatcher 不更新也不给出错误
【发布时间】:2016-02-07 12:23:46
【问题描述】:

我有一个应用程序,我需要下载很多文件。实际上要下载我使用此代码:

System.Net.ServicePointManager.DefaultConnectionLimit = Int32.Parse(Properties.Settings.Default["download_threads"].ToString());
var block = new System.Threading.Tasks.Dataflow.ActionBlock<string>(async url =>
{
    await DownloadLibraries(url);
}, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Int32.Parse(Properties.Settings.Default["download_threads"].ToString()) });

foreach (var url in urls)
{
    block.Post(url);
}

block.Complete();
await block.Completion;

它工作得很好,它可以通过并行下载下载我需要的所有内容。 在 DownloadLibraries 方法中,我想更新标签。 代码如下:

Application.Current.Dispatcher.Invoke(new Action(() =>
{
    string urlnum = this.filesToDownload.Content.ToString().Split('/')[0];
    if (Array.IndexOf(urls, url) > Int32.Parse(urlnum))
        this.filesToDownload.Content = Array.IndexOf(urls, url) + "/" + count.ToString();

    if ((Array.IndexOf(urls, url) * 100) > totalProgress.Value)
        this.totalProgress.Value = (Array.IndexOf(urls, url) * 100) / count;
}));

它没有给我任何错误,但它也没有更新标签。 如果我这样做 Console.Write((Array.IndexOf(urls, url) * 100) / count);它工作正常,我可以在 Visual Studio 的输出空间中看到百分比上升,但标签根本没有更新。可能是什么问题?

【问题讨论】:

  • 我使用类似的测试程序进行了尝试,对我来说,您的解决方案运行良好。您可以尝试将 MaxDegreeOfParallelism 设置为 1 吗?

标签: c# wpf multithreading dispatcher tpl-dataflow


【解决方案1】:

您应该在元素的Dispatcher 上调用.Invoke():

this.filesToDownload.Dispatcher.Invoke(new Action(() =>
{
    string urlnum = this.filesToDownload.Content.ToString().Split('/')[0];
    if (Array.IndexOf(urls, url) > Int32.Parse(urlnum))
        this.filesToDownload.Content = Array.IndexOf(urls, url) + "/" + count.ToString();

    if ((Array.IndexOf(urls, url) * 100) > totalProgress.Value)
        this.totalProgress.Value = (Array.IndexOf(urls, url) * 100) / count;
}));

【讨论】:

  • @giogiowefj 它正在运行吗?尝试在 Action 中放置一个断点。
猜你喜欢
  • 1970-01-01
  • 2013-06-26
  • 1970-01-01
  • 2019-09-22
  • 2022-01-19
  • 2014-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多