开发者

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

开发者 https://www.devze.com 2022-12-13 07:39 出处:网络
Suppose I have a routine like this: private void button1_Click(object sender, EventArgs e) { Thread t = new Thread(new ThreadStart(Some_Work));

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 runnin开发者_运维问答g apart from the Main thread, start a new thread".

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


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?


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

精彩评论

暂无评论...
验证码 换一张
取 消