Alternative to Thread.Suspend ()

Thread.Suspend()the method is deprecated, as you know. I want to temporarily suspend a stream when a button is pressed. I used Thread.Suspend () and it works great, but everyone thinks that using the Thread.Suspend () method is not a good method to pause a task. I used the flag to pause the task, but every time a button click event arrives, I have to wait to exit the task. I used the Thread.IsAlive flag to wait for the thread to exit, but this method freezes the form.

void ButtonClickEvent(object sender, ButtonClickEventArgs e)
{
    TheadExitFlag = false;

    if(MyThread != null)
    {
        while(MyThread.IsAlive);
        //MyThread.Suspend();
    }
}

void MyTask(void)
{
    while(TheadExitFlag)
    {
        // some process
        Thread.Sleep(5000);
    }
}

How can I temporarily suspend a thread?

+3
source share
3 answers

, AFAIK. , Suspend() /, , , , .

, , - "". AutoResetEvent .

+4

ManualResetEvent .

ManualResetEvent run = new ManualResetEvent(true);

void ResumeButton_Click(object sender, ButtonClickEventArgs e)
{
  run.Set();
  PauseButton.Enabled = true;
  ResumeButton.Enabled = false;
}

void PauseButton_Click(object sender, ButtonClickEventArgs e)
{
  run.Reset();
  PauseButton.Enabled = false;
  ResumeButton.Enabled = true;
}

void MyTask(void)
{
    while (run.WaitOne())  // Wait for the run signal.
    {
      // Do work here.
    }
}
+4
0

All Articles