[英]After click stop loop button, can't Start again
I use backgroundworker as suggested in the previous statement and it works. 我按照前面的声明中的建议使用backgroundworker,它可以工作。 but I have a new problem, that is after pressing the Stop button, the thread can't start again, must click 2 times 但是我有一个新问题,就是按下“停止”按钮后,该线程无法再次启动,必须单击2次
private bool _stopLoop;
private void button1_Click(object sender, EventArgs e)
{
this.BW_PING.RunWorkerAsync();
this.btPing.Enabled = false;
_stopLoop = false;
}
private void Ping(bool Type)
{
for (int i = 0; i < 100000 && !_stopLoop; ++i)
{
using (Ping p = new Ping())
{
Ping pingClass = new Ping();
PingReply pingReply = pingClass.Send(tbUrl.Text);
lbPing.Text = ("Ping - " + pingReply.RoundtripTime.ToString() + " Ms");
}
}
}
private void btStop_Click(object sender, EventArgs e)
{
_stopLoop = true;
this.btPing.Enabled = true;
lbPing.Text = ("Ping Stoped");
}
private void BW_PING_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bw = sender as BackgroundWorker;
Ping(true);
}
can anyone help me ? 谁能帮我 ?
There's a lot of things wrong with this code, for example why does the Ping(bool Type)
Method require a parameter even thought it's not used within the Method? 这段代码有很多问题,例如,为什么Ping(bool Type)
方法需要一个参数,甚至认为该方法中未使用该参数?
The simplest solution would be, as Hameed Syed pointed out in the comments, put _stopLoop = false;
如Hameed Syed在评论中指出的,最简单的解决方案是_stopLoop = false;
at the start of button1_Click
Method. 在button1_Click
方法的开头。 But it might be worth more redoing the entire thing 但是重做整个事情可能值得
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.