Threads

P

Peter K

Hi, I have a class "QControlThread" which in simplified form is like this:

public class QControlThread
{
private System.Threading.Thread m_thread;
private volatile Boolean m_stopping = false;

public void Start()
{
if (!m_stopping)
{
m_thread = new Thread(this.Worker);
m_thread.Start();
}
}

public void Stop()
{
m_stopping = true;
}

public void Worker()
{
while (!m_stopping)
{
// do work

Thread.Sleep(30000);
}
}
}

What I would like to know is, what if someone calls "Start" multiple times
on the instance of QControlThread? Would I then possibly have multiple
threads which I can't stop or access in any way?



Thanks,
Peter
 
J

Jon Skeet [C# MVP]

Hi, I have a class "QControlThread" which in simplified form is like this:

What I would like to know is, what if someone calls "Start" multiple times
on the instance of QControlThread? Would I then possibly have multiple
threads which I can't stop or access in any way?

Yes. You should probably stop them from doing that.

You might also want to look at using Monitor.Wait instead of
Thread.Sleep, so that when you ask a thread to stop it can do so
immediately rather than potentially waiting 30 seconds.

See my threading pages at http://pobox.com/~skeet/csharp/threads/ for
more information.

Jon
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

Peter said:
Hi, I have a class "QControlThread" which in simplified form is like this:

public class QControlThread
{
private System.Threading.Thread m_thread;
private volatile Boolean m_stopping = false;

public void Start()
{
if (!m_stopping)
{
m_thread = new Thread(this.Worker);
m_thread.Start();
}
}

public void Stop()
{
m_stopping = true;
}

public void Worker()
{
while (!m_stopping)
{
// do work

Thread.Sleep(30000);
}
}
}

What I would like to know is, what if someone calls "Start" multiple times
on the instance of QControlThread? Would I then possibly have multiple
threads which I can't stop or access in any way?

Insert the following in Start:

if(m_thread.IsAlive)
{
throw new Exception("Get your ¤&%"¤%"¤/!%&! hands of this Start
method");
}

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top