1

So I'm still fairly new to C#. Im learning about threads.

So far I would like to know how to check if a thread has ended. I know that i can put a bool at the end of the method the thread uses and use that to determine if the thread ends.. but i dont want to do that, mainly because i want to learn the right way

so far I have this.

Thread testThreadd = new Thread(Testmethod);
testThreadd.Start();
testThreadd.Join();

I read about the thread.join(); class. To my understanding, that class only prevents any code after that from executing.. Please help

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Jonny
  • 401
  • 2
  • 11

4 Answers4

4

Well there are different ways that give different results

1 ) Wait until the work has finished. This is exactly what you've got with your code already. You'll start a thread and then wait for that thread to finish before continuing execution.

thread.Start();
thread.Join();

2) thread.ThreadState will tell you whether or not the thread has finished. In a basic scenario you could do the following. This would allow you to check the current thread state at any point in your code where you've got access to the state.

if(thread.ThreadState != ThreadState.Running){
   // Thread has stopped
}

3) Using an event. A lot of Async examples will start some work and then trigger an event once the work has been completed. In this way you can sit watching for an event and respond once the work has completed. A usage example may look like the WebClient class

WebClient client = new WebClient();
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
Ian
  • 33,605
  • 26
  • 118
  • 198
1

Thread.Join method pauses current thread execution until second thread completes. It serves for thread synchronization and it's well enough indicator.

Otherwise, you should use Thread.IsAlive property to check if thread is running while not interrupting current thread. This property covers any state between Thread.Start and the end of the thread.

Elvedin Hamzagic
  • 825
  • 1
  • 9
  • 22
1

Thread.Join() Blocks the thread you call it on until the thread you have called Join() on returns. Extending the example you have above:

Thread testThreadd = new Thread(Testmethod);
testThreadd.Start();
testThreadd.Join();

//Do more stuff here. This stuff will not start until testThreadd has completed its work.
pquest
  • 3,151
  • 3
  • 27
  • 40
1

you can do this

public partial class MainWindow : Window
{
    Thread testThreadd;
    public MainWindow()
    {
        InitializeComponent();

        testThreadd = new Thread(Testmethod);

        testThreadd.Start();
        testThreadd.Join();
    }

    public void Testmethod()
    {
        // begining your treatement


        // Ending your treatement

        this.testThreadd.Abort();
    }

}
mister
  • 95
  • 6