3

I am using following code.

public void runThread(){
    if (System.Diagnostics.Process.GetProcessesByName("myThread").Length == 0)
    {
    Thread t = new Thread(new ThreadStart(go));
    t.IsBackground = true;
    t.Name = "myThread";
    t.Start();
    }
    else
    {
      System.Diagnostics.Debug.WriteLine("myThreadis already Running.");
    }   
}
public void go()
{
    //My work goes here
}

I am calling runThread() function many time but i want thread only start when thread is not running. How is it possible?

leppie
  • 115,091
  • 17
  • 196
  • 297
RAKESH HOLKAR
  • 2,127
  • 5
  • 24
  • 42
  • 1
    Do you create the thread only in run thread method? If it is so hold it as member and ask t.IsAlive or I miss something? – Sergey Kucher Oct 18 '12 at 07:15

5 Answers5

7

GetProcessesByName will not look for threads in your application but for processes in your machine. In fact there is no good way to get query for the threads in your own application (a matter aside is writing a debugger).

For what you want you could create a wrapper class for your threads in such way that you could query if they are running. Or keep track of the threads yourself by other means.

You could also consider to have a Lazy<Thread> field that will be initialized when needed, and you can query to see if the thread is till alive. After testing Lazy<Thread> is not a good idea.


Derived from Simon's answer:

private int running;

public void runThread()
{
    if (Interlocked.CompareExchange(ref running, 1, 0) == 0)
    {
        Thread t = new Thread
        (
            () =>
            {
                try
                {
                    go();
                }
                catch
                {
                    //Without the catch any exceptions will be unhandled
                    //(Maybe that's what you want, maybe not*)
                }
                finally
                {
                    //Regardless of exceptions, we need this to happen:
                    running = 0;
                }
            }
        );
        t.IsBackground = true;
        t.Name = "myThread";
        t.Start();
    }
    else
    {
        System.Diagnostics.Debug.WriteLine("myThreadis already Running.");
    }   
}

public void go()
{
    //My work goes here
}

*: Gotta catch'em all


Wajid and Segey are right. You could just have a Thread field. Allow me to provide the example:

private Thread _thread;

public void runThread()
{
    var thread = _thread;
    //Prevent optimization from not using the local variable
    Thread.MemoryBarrier();
    if
    (
        thread == null ||
        thread.ThreadState == System.Threading.ThreadState.Stopped
    )
    {
        var newThread = new Thread(go);
        newThread.IsBackground = true;
        newThread.Name = "myThread";
        newThread.Start();
        //Prevent optimization from setting the field before calling Start
        Thread.MemoryBarrier();
        _thread = newThread;
    }
    else
    {
        System.Diagnostics.Debug.WriteLine("myThreadis already Running.");
    }
}

public void go()
{
    //My work goes here
}

Note: It is better to use the first alternative (the one derived from Simon's answer) because it is thread-safe. That is, if there are various thread calling the method runThread simultaneously there is no risk of more than one thread being created.

Community
  • 1
  • 1
Theraot
  • 31,890
  • 5
  • 57
  • 86
  • Ok sir, I am trying and i will respond after some time. – RAKESH HOLKAR Oct 18 '12 at 08:25
  • I am using myPage.aspx page and i am getting every time thread.IsAlive==false when another request come to call runThread() function. – RAKESH HOLKAR Oct 18 '12 at 08:43
  • This may be either that the execution of the method go is too short or that the value of the thread field is not visible to other threads. I'll edit that alternative to address that. – Theraot Oct 18 '12 at 08:46
  • A problem with trying to track what Threads have been started in the class is that there is no guarantee that it is still running. If the thread was running a Windows Form or WPF screen, and the user exits the screen it would no longer be running. – John Foll Dec 08 '22 at 17:51
2

One easy way is that you could have a flag that indicates if it's running or not. You maybe have to use some lock if it's some conflicts.

public static bool isThreadRunning = false;

public void runThread()
{
    if (!isThreadRunning)
    {
        Thread t = new Thread(new ThreadStart(go));
        t.IsBackground = true;
        t.Name = "myThread";
        t.Start();
    }
    else
    {
      System.Diagnostics.Debug.WriteLine("myThreadis already Running.");
    }   
}
public void go()
{
    isThreadRunning = true;
    //My work goes here
    isThreadRunning = false;
}
Aalok
  • 553
  • 8
  • 21
Simon Edström
  • 6,461
  • 7
  • 32
  • 52
1

You can use Thread.IsAlive to check whether prevoius thread is running or not.This is to give the thread status.You can put this check before mythread.Start().

0

Do you create the thread only in run thread method? If it is so hold it as field of the class that holds runThread method and ask t.IsAlive.

Sergey Kucher
  • 4,140
  • 5
  • 29
  • 47
0

Maybe this can help you

static bool isRunning = false;
public void RunThread(){
    if (!isRunning)
    {
    Thread t = new Thread(()=> { go(); isRunning = true;});
    t.IsBackground = true;
    t.Name = "myThread";
    t.Start();
    }
    else
    {
      System.Diagnostics.Debug.WriteLine("myThread is already Running.");
    }   
}
public void go()
{
    //My work goes here
}
BD Magic
  • 17
  • 6