I create a new thread and start it from a main thread.
m_MyThread = new Thread(HandleMyThread);
m_MyThread.IsBackground = true;
m_MyThread.Start();
private void
I know this question is a bit old, but I thought I would post a response in case others come here.
For this example code, if it were changed to look like this:
Thread m_MyThread;
private void HandleMyThread()
{
while (true)
{
Thread.Sleep(5000);
return;
}
}
private void button1_Click(object sender, EventArgs e)
{
if (!m_MyThread.IsAlive)
{
m_MyThread = new Thread(HandleMyThread);
m_MyThread.IsBackground = true;
m_MyThread.Start();
}
}
This would create a new instance of the thread and start it. The ThreadStateException
error is because, simply, you can't re-start a thread that's in a stopped state. m_MyThread.Start()
is only valid for threads in the Unstarted
state. What needs done in cases like this is to create a new thread instance and invoke Start()
on the new instance.