0

I am using a WebClient to upload a string an retreive the answer from the server. To get the job done quicker, I decided to use the ThreadPool, but I need to know when all the downloads are over.

So far, I've been using a CountdownEvent which is supposed to decrease when the server's answer has been processed.

My main thread executes this :

CountdownEvent cde = new CountdownEvent(retour["contenu"].Count()); //Set the countdown with the number of Thread that needs to be created

foreach (var tab in retour["contenu"])
{
    App.AnniversaryViewModel.Items.Add(new Utilisateur(int.Parse((string)tab["id"])));
    System.Diagnostics.Debug.WriteLine("Création d'un utilisateur avec l'id : " + (string)tab["id"]);
    //System.Diagnostics.Debug.WriteLine("Le dernier utilisateur est : " + Items.Last<Utilisateur>().NOMPrenom);
    ThreadPool.QueueUserWorkItem(App.AnniversaryViewModel.Items.Last<Utilisateur>().telechargerLesInfos , cde); //Starts the download

}
//Waiting for every Thread to be done

cde.Wait();

System.Diagnostics.Debug.WriteLine("On a fini d'attendre");

And here is, in another class, the code that is supposed to be executed by each thread :

public void telechargerLesInfos(Object cde)
{

    APIWebTeam.sendRequest(RequestType.PROFIL, (Newtonsoft.Json.Linq.JObject reponse) =>
    {
        processInfos(reponse); //Takes the answer from the server and parse it to fill private fields
        ((CountdownEvent)cde).Signal();
    }, "&idProfil=" + id);

}

The thing is that the delegate refuses to execute, as if the "cde.Wait()" is also forcing the thread handling the delegate to wait. How can I fix / avoid that?

4

1 回答 1

2

首先,线程池在这里并没有真正做任何事情。您只是在线程池中启动异步操作。 启动这样的操作基本上不需要任何时间。您也可以在主线程中执行此操作。

至于为什么主线程被阻塞;这很容易,您自己通过等待倒计时事件来阻塞主线程。

在异步操作完成而不阻塞主线程之前,没有办法让主线程阻塞。它们实际上是相互矛盾的要求。

相反,您需要使整个程序异步,以避免阻塞主线程。例如,让这个方法接受一个回调,它应该在异步操作完成时执行。另一种选择是使用任务并行库。任务使处理异步操作变得相当容易,尤其是当您能够利用该await关键字时。

于 2013-12-23T16:34:05.240 回答