user366312
user366312

Reputation: 16894

How to know that I have another thread running apart from the main thread?

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?

Upvotes: 0

Views: 184

Answers (2)

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391276

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;
    }
}

Upvotes: 1

Tim Robinson
Tim Robinson

Reputation: 54724

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?

Upvotes: 2

Related Questions