C# : How to pause the thread and continue when some event occur?

半城伤御伤魂 提交于 2020-01-02 00:23:13

问题


How can I pause a thread and continue when some event occur?

I want the thread to continue when a button is clicked. Someone told me that thread.suspend is not the proper way to pause a thread. Is there another solution?


回答1:


You could use a System.Threading.EventWaitHandle.

An EventWaitHandle blocks until it is signaled. In your case it will be signaled by the button click event.

private void MyThread()
{
    // do some stuff

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

    // continue thread
}

You can signal your wait handle like this:

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



回答2:


Indeed, suspending a thread is bad practice since you very rarely know exactly what a thread is doing at the time. It is more predictable to have the thread run past a ManualResetEvent, calling WaitOne() each time. This will act as a gate - the controlling thread can call Reset() to shut the gate (pausing the thread, but safely), and Set() to open the gate (resuming the thread).

For example, you could call WaitOne at the start of each loop iteration (or once every n iterations if the loop is too tight).




回答3:


You can try this also

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();
    }


来源:https://stackoverflow.com/questions/4848064/c-sharp-how-to-pause-the-thread-and-continue-when-some-event-occur

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!