C#:如何暂停线程并在某些事件发生时继续?

时间:2011-01-31 06:01:49

标签: c# multithreading wait

如何暂停线程并在某些事件发生时继续?

我希望线程在单击按钮时继续。 有人告诉thread.suspend不是暂停线程的正确方法。 那另一个解决方案

3 个答案:

答案 0 :(得分:16)

您可以使用System.Threading.EventWaitHandle

EventWaitHandle阻塞,直到发出信号。在您的情况下,它将通过按钮单击事件发出信号。

private void MyThread()
{
    // do some stuff

    myWaitHandle.WaitOne(); // this will block until your button is clicked

    // continue thread
}

您可以发出如下信号:

private void Button_Click(object sender, EventArgs e)
{
     myWaitHandle.Set(); // this signals the wait handle and your other thread will continue
}

答案 1 :(得分:7)

实际上,暂停一个线程是不好的做法,因为你很少知道完全当时线程正在做什么。让线程超过ManualResetEvent,每次调用WaitOne()更为可预测。这将作为一个门 - 控制线程可以调用Reset()来关闭门(暂停线程,但安全),并Set()打开门(恢复线程)。

例如,您可以在每次循环迭代开始时调用WaitOne(如果循环太紧,则可以每n次迭代调用一次)。

答案 2 :(得分:3)

你也可以尝试这个

private static AutoResetEvent _wait = new AutoResetEvent(false);

public Form1()
    {
        InitializeComponent();
    }

private void Form1_Load(object sender, EventArgs e)
    {
        Control.CheckForIllegalCrossThreadCalls = false;
        backgroundWorker1.RunWorkerAsync();
    }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        Dosomething();
    }

private void Dosomething()
{
 //Your Loop
 for(int i =0;i<10;i++)
   {
    //Dosomething
    _wait._wait.WaitOne();//Pause the loop until the button was clicked.

   } 
}

private void btn1_Click(object sender, EventArgs e)
    {
        _wait.Set();
    }