# [C#]How to check if the main thread is still running?



## rabidgnome229

By running do you mean that it isn't blocked or that it hasn't terminated?


----------



## xEnt

Thread.CurrentThread.State i cant check right now if thats exact, but it has the thread's state's somewhere around there.


----------



## killnine

System.Threading.ThreadState

That is the enum that describes the state of a paricular thread. If you have an instance of a thread (wouldn't this be hard with the main thread?), you can just call this to see what its value is.

Checking the state of the main thread seems, to me, to be a difficult task. If its locked, your whole GUI should be frozen, and its likely that unless you have background workers going on, you wont even get a response from the query. =P


----------



## Licht

Quote:


Originally Posted by *rabidgnome229* 
By running do you mean that it isn't blocked or that it hasn't terminated?

I'm making sure the main thread hasn't closed. As if it has the user has exited the application, but that doesn't mean the other threads which are in loops have closed. So i want to check periodically if the main thread is closed or not. If it is end the thread. But i can't find a way to reference the main thread.


----------



## rabidgnome229

Quote:


Originally Posted by *Licht* 
I'm making sure the main thread hasn't closed. As if it has the user has exited the application, but that doesn't mean the other threads which are in loops have closed. So i want to check periodically if the main thread is closed or not. If it is end the thread. But i can't find a way to reference the main thread.

Periodic checks will probably be fairly expensive (depends on how often/how you implement it). I would suggest either waiting for the loops to terminate as a part of the main thread's closing or using some sort of exceptional control flow to do any cleanup work you need to do in the child threads and terminate them.


----------



## Licht

Quote:


Originally Posted by *rabidgnome229* 
Periodic checks will probably be fairly expensive (depends on how often/how you implement it). I would suggest either waiting for the loops to terminate as a part of the main thread's closing or using some sort of exceptional control flow to do any cleanup work you need to do in the child threads and terminate them.

Its a stress test for my application so i am not worried about expense.


----------



## linskingdom

Do you want to block the user to run another instance of application? If so, then there is a property/option in each project named 'make single instance application'. Just check the box.

Or add this to the load or run,

Process process = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(process.ProcessName);
if (processes.Length > 0)
{

//He can't run
}


----------



## Licht

Quote:


Originally Posted by *linskingdom* 
Do you want to block the user to run another instance of application? If so, then there is a property/option in each project named 'make single instance application'. Just check the box.

No i want to close a thread if it detects the main thread has closed.


----------



## linskingdom

There are many ways to do so but instead of looping to check the main thread, I would create a delegate associate with call back in the main thread close/end. If main thread stops because of errors or completed, it will triggle the call back to terminate/close/abort all remaining thread.


----------



## Licht

Quote:


Originally Posted by *linskingdom* 
There are many ways to do so but instead of looping to check the main thread, I would create a delegate associate with call back in the main thread close/end. If main thread stops because of errors or completed, it will triggle the call back to terminate/close/abort all remaining thread.

You have the code to do that? It would be nice to simply set up an event with some code instead of edit my carefully optimized loops.


----------



## linskingdom

I am on a trip and don't have c# on my laptop. Since you have an optimized method to track the threads, you are doing fine. Depending on how to run the thread, here is what I normally do.

1. Define a static array to hold all threads. m_MyThreads_ = m_NewThreads.Id when a thread starts it.

2.Let's say you have a form to host all process. youForm is a form object.

3. Define a delegate to call back so won't intercupt all threads.
public delegate void NeedToCloseAllThreads();

4. Define a delegate methods that are called from the main thread.
public NeedToCloseAllThreads m_ NeedToCloseAllThreads;

5. Define a call back method
Public function CloseThreadsDetails()
{
// loop m_MyThreads to check the rest of threads.
// If each thread state is open, close or abort
// If each thread var is null, do nothing.
// release thread resource

};

6. Initial the main thread
m_ NeedToCloseAllThreads = new NeedToCloseAllThreads (this.CloseThreadsDetails);

7. // Add code to main thread
Try
{
// code to do in the main thread

// When the main thread completed, close all threads
youForm.Invoke(youForm.m_ NeedToCloseAllThreads);

}
Catch
{
// error in main thread, need to close all threads too.
youForm.Invoke(youForm.m_ NeedToCloseAllThreads);
}_


----------



## ghell

It sounds like you just want to use a background thread for your "other" thread. Background threads will not keep the application alive so if your "main" thread is the only foreground thread, when this terminates, the application will terminate.

System.Threading.Thread.IsBackground {get; set;}


----------



## Licht

Quote:


Originally Posted by *ghell* 
It sounds like you just want to use a background thread for your "other" thread. Background threads will not keep the application alive so if your "main" thread is the only foreground thread, when this terminates, the application will terminate.

System.Threading.Thread.IsBackground {get; set;}

Will the threads keep the same amount of processing time?


----------



## ghell

Quote:


Originally Posted by *Licht* 
Will the threads keep the same amount of processing time?

I do not know what you mean. However, it does what you ask for. If the "main" thread was the only foreground thread, and it terminates, none of the "background" threads keep the application open. They do not get a lower priority or anything like this.

As an example, if you wanted to download a large file from the internet and someone closed the application: Using a foreground thread to download it would mean that the process remains active until the download is complete. Using a background thread, the thread automatically terminates when every other foreground thread has terminated and, as the process has terminated, the download does not complete.

The only difference is that background threads do not keep the process open on their own.


----------



## Licht

Something occurred to me while trying to reference a thread management thread.

Code:



Code:


Thread MainThread = Thread.CurrentThread;

Wouldn't that allow me to reference the main thread?

Code:



Code:


if (MainThread.IsAlive == false)
{
      Thread.CurrentThread.Abort();
}

Have that iterate *very* uncommonly, plus it would wind up being more efficient then my last release since i optimized out 3 cycles per iteration since last release.


----------



## ghell

If you call that from the main thread, yes.

something like this:

Code:



Code:


using System.Threading;

class Program
{
  public static Thread MainThread;

  static void Main()
  {
    MainThread = Thread.CurrentThread;

    // .. go and do something in a different thread that accesses Program.MainThread
  }
}

If you use Thread.CurrentThread in the worker thread, it will give you the instance of the worker thread, not the main thread.

However, from all of your posts it sounds like all you want to do is stop the worker thread from keeping the application open, so that when the main thread closes, the whole process exits. This is what background threads are for and just setting

Code:



Code:


myThread.IsBackground = True;
myThread.Start();

when you want to start the thread is all you need to do.


----------



## Licht

Quote:


Originally Posted by *ghell* 
However, from all of your posts it sounds like all you want to do is stop the worker thread from keeping the application open, so that when the main thread closes, the whole process exits. This is what background threads are for and just setting

Code:



Code:


myThread.IsBackground = True;
myThread.Start();

when you want to start the thread is all you need to do.

Ok, ok, i get it now, thanks.


----------

