user979033
user979033

Reputation: 6490

How to wait until my thread is finished

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.

Upvotes: 1

Views: 4383

Answers (3)

Matt Burland
Matt Burland

Reputation: 45155

You want 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 BackgroundWorker class.

Upvotes: 2

JaredPar
JaredPar

Reputation: 755557

To wait for the 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. Assuming getStatistics returns a 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);
  });
}

Upvotes: 1

Daniel Mošmondor
Daniel Mošmondor

Reputation: 19986

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.

Upvotes: 0

Related Questions