Cómo esperar hasta que termine mi hilo

private void showStatistics(string path)
{
    Thread thread = new Thread(() =>
        {
            Statistics myClass= new Statistics(path);
            list = myClass.getStatistics();
        });

    thread.Start();

    foreach (KeyValuePair<string, string> item in list )
    {
        listBoxIps.Items.Add(item.Key + item.Value + "\n");
    }
}

I want to wait until thread has finish its job and then start the foreach, when I put the foreach in the thread, cross threading error received.

preguntado el 10 de marzo de 12 a las 16:03

3 Respuestas

¿Quieres thread.Join. But that's probably not exactly what you are trying to do (because Join will block, in which case why even use a separate thread in the first place). Look into the FondoTrabajador clase.

respondido 10 mar '12, 19:03

Also, look into and understand Form.Invoke. You can have your thread, at its completion, call a method in your form, but it must do it using Invoke... if your ' after thread logic' does anything with any Controls. - sethcall

Para esperar el Thread to complete you can use the Join API. However that's likely not what you want in this scenario. A Join here would cause the entire UI to block until the Thread completed which would defeat the purpose of having the thread in the first place.

An alternate design is to spawn of the Thread and have it call back into the UI once it's complete via BeginInvoke. Asumiendo getStatistics devuelve un List<KeyValuePair<string, string>.

private void showStatistics(string path) {
  Action<List<KeyValuePair<string, string>> action = list => {
    foreach (KeyValuePair<string, string> item in list ) {
      listBoxIps.Items.Add(item.Key + item.Value + "\n");
    }
  };

  Thread thread = new Thread(() => {
    Statistics myClass= new Statistics(path);
    list = myClass.getStatistics();
    this.BeginInvoke(action, list);
  });
}

respondido 10 mar '12, 18:03

Create shared variable, and use it to signal finish of the thread. In the loop, after thread is started, do:

while (!finished)
{
     Application.DoEvents();
     Thread.Sleep(10);
}

Your problem is that you want your UI to be responsive while list is filled. That will ensure it.

respondido 10 mar '12, 16:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.