How to start a stopped thread

前端 未结 5 2052
孤城傲影
孤城傲影 2021-02-14 10:53

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         


        
相关标签:
5条回答
  • 2021-02-14 11:01

    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.

    0 讨论(0)
  • 2021-02-14 11:03

    To restart a thread, try this:

    private void button1_Click(object sender, EventArgs e)
    {
        // Just create a new constructor for the stopped Thread
        m_MyThread = null;
        m_MyThread = new Thread(HandleMyThread);
        m_MyThread.IsBackground = true;
        // Then restart the stopped Thread
        m_MyThread.Start();
    }
    

    This works if the thread was previously stopped.

    0 讨论(0)
  • 2021-02-14 11:09

    Use a ManualResetEvent, and instead of Thread.Sleep, wait for the event with a timeout.

    Then, any other thread can activate the event, and immediately resume the sleeping thread.

    Once a thread is exited, it can no longer run. So don't let it exit. Instead, put it back to sleep waiting for an event.

    0 讨论(0)
  • 2021-02-14 11:16

    Just make a new thread like you did when you initially created the thread. You might also want to pull that out into a method to avoid repeating yourself.

    0 讨论(0)
  • 2021-02-14 11:27

    If you want to reuse the thread without new a thread every time , you can consider the implementation of thread pool.

    0 讨论(0)
提交回复
热议问题