Application Dispatcher不会更新,也不会出错

时间:2016-02-07 12:23:47

标签: c# wpf multithreading dispatcher tpl-dataflow

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

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);它工作正常,我可以在视觉工作室的输出空间中看到百分比上升,但标签根本没有更新。可能是什么问题?

1 个答案:

答案 0 :(得分:0)

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

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;
}));