[英]WaitOne() doesnot wait in ManualResetEvent
I think its not waiting at run.waitOne(); 我认为它不会在run.waitOne();
here while processing the line of code,suppose i want to pause these lines of code by clicking the pause button.It should wait once again i click the same pause to resume same thread.But it doesnot wait at all.Any idea to achieve this? 在处理代码行时,假设我想通过单击暂停按钮来暂停这些代码行。它应该再次等待我点击相同的暂停以恢复相同的线程。但它不会等待。任何想法都可以实现这一点?
ManualResetEvent run=new ManualResetEvent(false);
bool flag=true;
StartButton_Click(object sender,EventArgs e)
{
ThreadStart ts=new ThreadStart(startprocess);
Thread th=new Thread(ts);
th.Start();
}
private void StartProcess()
{
while(true)
{
if (parentform != null)
{
TestForm(parentform);
parentform = null;
}
else
{
if (a[0] == true)
{
value[0] = method1();//method1 return a double value
Thread.Sleep(500);
}
if (a[1] == true)
{
value[1] =method2();
Thread.Sleep(500);
}
if (a[2] == true)
{
value[2] = method3();
Thread.Sleep(500);
}
if (a[3] == true)
{
value[3] = method4();
Thread.Sleep(500);
}
if (a[4] == true)
{
value[4] =method5();
Thread.Sleep(500);
}
if (a[5] == true)
{
value[5] = method6();
Thread.Sleep(500);
}
run.WaitOne();
timer1.Stop();
DateTime now = DateTime.Now;
string datetime = Convert.ToString(now);
database.InsertTest(datetime,value[0], value[1], value[2], value[3], value[4],value[5]);
}
}
}
private void Pausebutton_Click(object sender, EventArgs e)
{
if (flag)
{
timer1.Enabled = true;
run.Set();
flag = false;
}
else
{
timer1.Enabled = false
run.Reset();
flag = true;
}
}
You've got Reset
and Set
the wrong way round - you're trying to make it wait if it's already wait... otherwise, you're setting the event, saying "Keep going." 你有Reset
和Set
错误的方式 - 如果它已经等待你试图让它等待...否则,你正在设置事件,说“继续前进”。
I'd also add that relying on the state of the thread is a bad idea - you should keep track of whether or not you're logically paused, and set/reset the event accordingly. 我还补充说,依赖线程的状态是一个坏主意 - 你应该跟踪你是否在逻辑上暂停,并相应地设置/重置事件。 Otherwise, you've got an awkward situation where two clicks of the button in quick succession might pause and then unpause it, or it might just pause it twice. 否则,你有一个尴尬的情况,快速连续两次点击按钮可能暂停然后取消暂停,或者它可能只是暂停两次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.