I finally figure out how to solve my problem, the thing is despite that I am firing my download event asynchronous it seems they still are executed on the main thread, which mean that this.CountDown.Wait()
is being invoked before that any download is completed then my this.CountDown
is not being signaled therefore this.CountDown
never is set to zero and this remains waiting.
Here what I did:
Into the foreach
I replaced the call to the method LoadSources(uri)
by a ThreadPool.QueueUserWorkItem which queues a method for execution. The method executes when a thread pool thread becomes available.
ThreadPool.QueueUserWorkItem(new WaitCallback(LoadSources), (object)uri);
I also had to change the LoadSources method to fit my adjustments.
private void LoadSources(object uri)
{
WebClient client = new WebClient();
client.DownloadStringAsync(new Uri(uri.ToString(), UriKind.Absolute));
client.DownloadStringCompleted += (s, a) =>
{
lock (thisLock)
{
try
{
if (a.Error == null && !a.Cancelled)
{
this.Text.Add(a.Result);
}
}
finally
{
this.CountDown.Signal();
}
}
};
}
And as you can see I added a lock statement to avoid that two or more threads try to call this.Text.Add
simultaneously
Before that I just declared a private object to lock on.
private Object thisLock = new Object();