How to Check If Thread Finished Execution

How to check if Thread finished execution

Use the Thread.IsAlive flag. This is to give the thread status.

c# How to check a thread is finished before starting another one

If you want only one thread running at a time, then you can create a field to store Thread instance. Using that thread instance you can check if it's already running or not by using _threadInstance.IsAlive.

private Thread _bluetoothSearchThread;
private void timerScreenRefresh_Tick(object sender, EventArgs e)
{
if(_bluetoothSearchThread != null && _bluetoothSearchThread.IsAlive)
return; //It means one thread is already performing the search operation.

if (LocalUtilities.Debug > 3) LocalUtilities.writeLogFile(4, "Primary", LocalUtilities.getCurrentMethod() + "()", "");

// If the user is not on a Remote desktop connection
if (!remoteDesktopUser)
{

// Run the Bluetooth Search in a worker thread
_bluetoothSearchThread = new Thread(new ThreadStart(this.checkProximity));
_bluetoothSearchThread.IsBackground = true;
_bluetoothSearchThread.Start();
}

// Load User Data from the DB and display on the screen
loadUserData();
}

How to know if other threads have finished?

There are a number of ways you can do this:

  1. Use Thread.join() in your main thread to wait in a blocking fashion for each Thread to complete, or
  2. Check Thread.isAlive() in a polling fashion -- generally discouraged -- to wait until each Thread has completed, or
  3. Unorthodox, for each Thread in question, call setUncaughtExceptionHandler to call a method in your object, and program each Thread to throw an uncaught Exception when it completes, or
  4. Use locks or synchronizers or mechanisms from java.util.concurrent, or
  5. More orthodox, create a listener in your main Thread, and then program each of your Threads to tell the listener that they have completed.

How to implement Idea #5? Well, one way is to first create an interface:

public interface ThreadCompleteListener {
void notifyOfThreadComplete(final Thread thread);
}

then create the following class:

public abstract class NotifyingThread extends Thread {
private final Set<ThreadCompleteListener> listeners
= new CopyOnWriteArraySet<ThreadCompleteListener>();
public final void addListener(final ThreadCompleteListener listener) {
listeners.add(listener);
}
public final void removeListener(final ThreadCompleteListener listener) {
listeners.remove(listener);
}
private final void notifyListeners() {
for (ThreadCompleteListener listener : listeners) {
listener.notifyOfThreadComplete(this);
}
}
@Override
public final void run() {
try {
doRun();
} finally {
notifyListeners();
}
}
public abstract void doRun();
}

and then each of your Threads will extend NotifyingThread and instead of implementing run() it will implement doRun(). Thus when they complete, they will automatically notify anyone waiting for notification.

Finally, in your main class -- the one that starts all the Threads (or at least the object waiting for notification) -- modify that class to implement ThreadCompleteListener and immediately after creating each Thread add itself to the list of listeners:

NotifyingThread thread1 = new OneOfYourThreads();
thread1.addListener(this); // add ourselves as a listener
thread1.start(); // Start the Thread

then, as each Thread exits, your notifyOfThreadComplete method will be invoked with the Thread instance that just completed (or crashed).

Note that better would be to implements Runnable rather than extends Thread for NotifyingThread as extending Thread is usually discouraged in new code. But I'm coding to your question. If you change the NotifyingThread class to implement Runnable then you have to change some of your code that manages Threads, which is pretty straightforward to do.

how to test result when thread is finished - java

Case 1: Do stuff, then wait for results, then continue.

myThread.join() is for cases when the code that created the thread does some more stuff after starting the thread, and then wants to wait for the thread's result. Once the thread's code is done, the thread dies, and thus the application continues execution after the join() call.

To give the application information from the thread, you'd have to store it somewhere, e.g. in a field dedicated for this. You don't have to worry about synchronization, because once the thread has died, all its actions will become "common knowledge", they are not privately timed (or whatever) any more.

Case 2: Keep doing stuff, and regularly check if results are available.

If instead your intention is to have some kind of game loop, where you keep doing stuff, and your extra thread is only meant to deliver some goods to you eventually (e.g. render a star background image while your game is already running), again you should hand it to the application in a field (aka class variable).

In that case, though, you have to worry about synchronization. Because as the game loop keeps checking if the field has changed from null to a value, the two threads are racing each other.

So, in that case you'd need an extra object to synchronize on, ideally a dedicated one for this task, e.g. final private Object lockForBackgroundCalculation = new Object();, and when the thread writes its result value into the other field, you wrap that statement into synchronized(lockForBackgroundCalculation){...}, and you also wrap your game loop's checking of the field value into the very same sync block text.

how to know if thread execution is terminated?

There are few simple things you can do.

You could use Thread.Join to see if the thread has ended.

var thread = new Thread(SomeMethod);
thread.Start();
while (!thread.Join(0)) // nonblocking
{
// Do something else while the thread is still going.
}

And of course if you do not specify a timeout parameter then the calling thread will block until the worker thread ends.

You could also invoke a delegate or event at the end of entry point method.

// This delegate will get executed upon completion of the thread.
Action finished = () => { Console.WriteLine("Finished"); };

var thread = new Thread(
() =>
{
try
{
// Do a bunch of stuff here.
}
finally
{
finished();
}
});
thread.Start();

How to check if the threads have completed its task or not?

A good way to use threads is not to use them, directly. Instead make a thread pool. Then in your POJO task encapsulation have a field that is only set at the end of computation.

There might be 3-4 milliseconds delay when another thread can see the status - but finally the JVM makes it so. As long as other threads do not over write it. That you can protect by making sure each task has a unique instance of work to do and status, and other threads only poll that every 1-5 seconds or have a listener that the worker calls after completion.
A library I have used is my own
https://github.com/tgkprog/ddt/tree/master/DdtUtils/src/main/java/org/s2n/ddt/util/threads

To use : in server start or static block :

package org.s2n.ddt.util;

import org.apache.log4j.Logger;
import org.junit.Test;

import org.s2n.ddt.util.threads.PoolOptions;
import org.s2n.ddt.util.threads.DdtPools;

public class PoolTest {
private static final Logger logger = Logger.getLogger(PoolTest.class);

@Test
public void test() {
PoolOptions options = new PoolOptions();
options.setCoreThreads(2);
options.setMaxThreads(33);
DdtPools.initPool("a", options);
Do1 p = null;
for (int i = 0; i < 10; i++) {
p = new Do1();
DdtPools.offer("a", p);

}
LangUtils.sleep(3 + (int) (Math.random() * 3));
org.junit.Assert.assertNotNull(p);
org.junit.Assert.assertEquals(Do1.getLs(), 10);
}

}

class Do1 implements Runnable {
volatile static long l = 0;

public Do1() {
l++;

}

public void run() {

// LangUtils.sleep(1 + (int) (Math.random() * 3));
System.out.println("hi " + l);
}

public static long getLs() {
return l;
}
}

Things you should not do:
* Don't do things every 10-15 milliseconds
* Unless academic do not make your own thread
* don't make it more complex then it needs for 97% of cases

check if thread finished its method before killing it c#

However if I kill the WorkerThread while it's in the middle of a method it sometimes causes a problem in my word document

This is why you should never kill a thread. You can't say what the thread was doing, whether it is safe to kill? etc etc.

Abort isn't doing what you expect it to do. Look at the documentation, it is subtle Calling this method usually terminates the thread. Note the word usually and not always.

Yes, Abort will not kill the thread always. For example if the thread was running unmanaged code, CLR will not abort the thread, instead it will wait for the thread to return to managed code.

Sameway Abort will not do its job when thread is in Constrained Execution Region, finally blocks etc.

The CLR delays thread aborts for code that is executing in a CER.

For example: Try to run the following code and see what happens.

private void IWillNeverReturn()
{
Thread thread = new Thread(() =>
{
try
{
}
finally
{
while (true)
{ }
}
});
thread.Start();

Thread.Sleep(1000);
thread.Abort();
}

Let the thread decide when it should complete, Tell the thread that it should stop as soon as it can. You tell it using CancellationToken.

If you google for Thread.Abort Evil, you'll find lot of useful resources, Here is one.



Related Topics



Leave a reply



Submit