Click here to Skip to main content
15,886,634 members
Please Sign up or sign in to vote.
3.67/5 (3 votes)
See more:
I am learning threading and I was wondering if there was a way to check if a thread was working or not, something like this.

VB
If thread1.working then
    thread2.join()
    thread2 = new thread(address of somemethod)
    thread2.start()
else
    thread1.join()
    thread1 = new thread(address of somemethod)
    thread1.start()
end if


I am not looking for code, just resources on how this would work.
Posted
Comments
Sergey Alexandrovich Kryukov 17-Dec-12 10:04am    
Why, exactly?
—SA

That depends on what you mean by "working". You can only get the status of a thread (IsRunning), but you cannot get the status of the code it's executing.

The only way to do that would be to rewrite the code your background thread is running to provide some sort of "heartbeat" or some other status variable or events that your parent code can check or subscribe to.
 
Share this answer
 
Comments
Daniel Verbatim Hallam 17-Dec-12 9:22am    
Would I be right to assume that once the method the thread is executing has completed the thread would no longer be running?
Dave Kreskowiak 17-Dec-12 9:33am    
Once the the code is done the thread dies. It will no longer be running.
Do you mean Managed Thread States [^]?
 
Share this answer
 
Comments
Daniel Verbatim Hallam 17-Dec-12 9:24am    
Thats a useful link too, I was looking for something like that, thank you.
CPallini 17-Dec-12 9:33am    
you are welcome.
Sergey Alexandrovich Kryukov 17-Dec-12 9:57am    
This is useful, good to know, my 5, but...

It's much better not to poll the thread at all and not depend on return. It's much better to design a thread to notify require set on completion; another approach is to wait for thread completion by Join, which is a blocking code, without wasteful polling; is some situations, this is exactly what should be done.

This way, the real solution of the problem depends on the purpose OP did not share with us.
—SA
Espen Harlinn 17-Dec-12 12:33pm    
5'ed!
CPallini answered you, but the polling of the thread for status is a sign of really wrong design.

In some situations, you need a blocking call System.Threading.Thread.Join. The calling thread will be put in wait state, sleeping without wasting any CPU cycles, until awakened by completion. Please see:
http://msdn.microsoft.com/en-us/library/system.threading.thread.join.aspx[^].

I see you already trying "if (working) thread.Join()", but this is pointless, really. Explain what you are trying to achieve, the purpose of it.

In other cases, it's the best for a thread to notify other threads on completion. How? It depends. Please see my comments to Solution 2.

—SA
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900