C# : How to pause the thread and continue when some event occur?
How can I pause a thread and continue when 开发者_Go百科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?
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
}
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).
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();
}
精彩评论