如果我有无限循环while(true)我如何使用外部标志停止/继续循环?

如果我有无限循环while(true)我如何使用外部标志停止/继续循环?

问题描述:

我需要做的是添加一个按钮或两个标志,将停止/继续循环。 我该怎么做?如果我有无限循环while(true)我如何使用外部标志停止/继续循环?

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

我的建议是去阅读MSDN上这里的示例代码:BackgroundWorker Class (MSDN)。他们的例子显示了取消工人的方式。


您还可以使用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); 
    } 
} 
+0

SpinWait好得多 – GSerjo 2012-08-05 17:01:22

+0

的方法和现在你有2个问题,P – leppie 2012-08-05 17:01:46

创建具有消除一个布尔和暂停状态的自定义类。 在您的backgroundWorker.DoWork([MyCustomObject的实例])中传递该类中的对象参数

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

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); 
    } 
} 
+0

在NED我使用BackgroundWorker的取消未完成的选项。谢谢。 – user1544479 2012-08-05 17:19:43

首先你做一个方法来完成任务。然后声明Threading类的实例作为

Threading thrd=new Threading(signature of method defined) 

然后写在任何你想要的按钮的事件处理程序。

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

的启动,停止或恢复线程