如果我有无尽的循环,而(true)我如何使用外部标志来停止/继续循环



我需要做的是添加一两个带有停止/继续循环标志的按钮。我该怎么做?

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    while(true)
    {
        cpuView();
        gpuView();
        Thread.Sleep(1000);
    }
}

我的建议是在这里阅读MSDN上的示例代码:BackgroundWorker class(MSDN)。他们的示例显示了取消工作者的proper方法。


您也可以使用break退出循环:

bool stop = false;
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    while(true)
    {
        if(stop)
            break; // this will exit the while loop
        cpuView();
        gpuView();
        Thread.Sleep(1000);
    }
}

创建一个自定义类,该类具有用于取消和暂停状态的布尔值。在您的backgroundWorker.DoWork(〔instance of MyCustomObject here〕)args 中传递该类的对象

您可以使用按钮事件从原始线程更新属性。

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    MyCustomObject cancellationStatus = e.Argument as MyCustomObject
    while(!cancellationStatus.Cancelled)
    {
        if(!cancellationStatus.Paused)
        {
            cpuView();
            gpuView();
        }
        Thread.Sleep(1000);
    }
}

首先,您创建一个执行任务的方法。然后将类Threading的实例声明为

Threading thrd=new Threading(signature of method defined)

然后在您想要的任何按钮中编写一个事件处理程序。

t.start()
t.abort()
t.resume()

是启动、停止或恢复线程的方法

相关内容

最新更新