views:

57

answers:

2

Suppose I have a routine like this:

private void button1_Click(object sender, EventArgs e)
{
    Thread t = new Thread(new ThreadStart(Some_Work));
    t.Start();
}

I need to put a condition so that, "If there is not already a thread running apart from the Main thread, start a new thread".

But how to test for whether a thread is running other than the Main thread?

+2  A: 

There's several other threads running in your .NET app before it even gets to button1_Click. For instance, the finalizer thread is always hanging around, and I think WinForms creates one or two for itself.

Do you need to know about other threads that you've created? If so, you should keep track of them yourself. If not: why?

Edit: are you looking to kick off some background processing on demand? Have you seen the BackgroundWorker component, which manages threads for you, together with their interaction with the user interface? Or direct programming against the thread pool, using Delegate.BeginInvoke or ThreadPool.QueueUserWorkItem?

Tim Robinson
In addition, Win32 creates and stops its own threads when it wants. E.g., showing a standard Open File dialog will create a couple of threads (and non-standard shell extensions may create even more); `QueueUserWorkItem()` may create additional threads for system thread pool, etc.
atzz
It answers your question. I'm still not sure why the information is useful: it's always going to return > 1 in a .NET app.
Tim Robinson
That's more like it, although not sure you need the 'IsAlive' check if you've got the '!= null' check.
Tim Robinson
+1  A: 

The easiest solution is of course to either store a reference to the existing thread, or just set a flag that you have a thread running.

You should also maintain that field (reference or flag) so that if the thread exits, it should unset that field so that the next "start request" starts a new one.

Easiest solution:

private volatile Thread _Thread;

...

if (_Thread == null)
{
    _Thread = new Thread(new ThreadStart(Some_Work));
    _Thread.Start();
}

private void Some_Work()
{
    try
    {
        // your thread code here
    }
    finally
    {
        _Thread = null;
    }
}
Lasse V. Karlsen