C# 停止来自另一个类的类中的循环
所以我有两个事件处理程序button1\u Click()和button2\u Click() 在button1_Click()中,我有如下运行方式:C# 停止来自另一个类的类中的循环,c#,.net,loops,C#,.net,Loops,所以我有两个事件处理程序button1\u Click()和button2\u Click() 在button1_Click()中,我有如下运行方式: toGet = textbox1.Text; got = 0; while (got <= toGet) { //DoStuff } toGet=textbox1.Text; got=0; while(gotWindows.Forms-answer 最不复杂的方法是: private bool m_stop; private voi
toGet = textbox1.Text;
got = 0;
while (got <= toGet)
{
//DoStuff
}
toGet=textbox1.Text;
got=0;
while(gotWindows.Forms-answer
最不复杂的方法是:
private bool m_stop;
private void button1_Click (object s, EventArgs ea)
{
try
{
// Don't forget to disable all controls except the ones you want a user to be able to click while your method executes.
toGet = textbox1.Text;
got = 0;
while (got <= toGet)
{
Application.DoEvents ();
// DoEvents lets other events fire. When they are done, resume.
if (m_stop)
break;
//DoStuff
}
finally
{
// Enable the controls you disabled before.
}
}
private void button2_Click (object s, EventArgs ea)
{
m_stop = true;
}
private bool m_stop;
私有无效按钮1\u单击(对象、事件参数)
{
尝试
{
//别忘了禁用所有控件,除了希望用户在方法执行时能够单击的控件。
toGet=textbox1.Text;
got=0;
虽然(得到了我所理解的,但如果我错了,请纠正我,因为你是在单线程上。
有线连接,但您可以检查While循环中的单个布尔值,正如post建议的那样
可能是为了让生活更轻松(可能这就是“无法让它工作”的意思)是内部循环调用
1) Windows窗体:Application.DoEvents()
2) WPF(稍微复杂一点):
这将创建呼吸系统。您需要在新线程中的按钮1
内启动流程,当您按下按钮2
时,将局部变量标记为false以停止循环。例如:
using System.Threading;
private volatile bool _requestStop = false;
private readonly object _oneExecuteLocker = new object();
private void OnButton1Click(ojbect sender, EventArgs e)
{
new Thread(() =>
{
if (Monitor.TryEnter(_oneExecuteLocker))
{//if we are here that is means the code is not already running..
try
{
while (!_requestStop)
{
//DoStuff
}
}
finally
{
Monitor.Exit(_oneExecuteLocker);
}
}
}){ IsBackground = true }.Start();
}
private void OnButton2Click(object sender, EventArgs e)
{
_requestStop = true;
}
注:
- 当您想要更新新创建的线程中的UI控件时,您应该使用
contorl.Invoke(/*UI*/中的code get/set或call方法)
Monitro.Enter
只是为了确保您的代码在每次单击时不会执行多次(如果代码已经运行)
您是否在一个线程中运行,如您链接到的问题的公认答案所述?Winforms?WebForms?WPF?请告诉我发生了什么。“无法使其工作”没有多大帮助。当我这样做时,我得到了“m_stop”的名称在Buto1ApDead这个上下文中不存在于您的类中:<代码>私有BoOL MySturt;< /COD> > 1,用于计时器。但是考虑到您的“单线程规则”只能使用Syt.WeloW.Fr.St.Time.如果这是WiFrm(尚未真正清楚)<代码>应用程序. doEVER()
是一个非常糟糕的建议,它带来的问题比它真正解决的问题还多。啊,我想出来了。只是把stop变成了一个全局变量