0

I have an application and i need to download a lot of files. Actually to download i use this code:

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;

It works just fine, it downloads everything i need with parallel downloads. Inside the DownloadLibraries method i want to update a label. Here is the code:

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

It doesn't give me any error but it doesn't update the label either. If i do Console.Write((Array.IndexOf(urls, url) * 100) / count); it works fine, i can see in the output space in visual studio the percentage going up but the label doesn't update at all. What could be the problem?

giogiowefj
  • 103
  • 7
  • I tried it with a similar test program and for me your solution worked perfectly. Could you try setting MaxDegreeOfParallelism to 1? – Istvan Reiter Feb 07 '16 at 14:52

1 Answers1

0

You should call .Invoke() on the element's 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;
}));
AgentFire
  • 8,944
  • 8
  • 43
  • 90