gpt4 book ai didi

c# - 在不中断程序的情况下创建无限循环

转载 作者:行者123 更新时间:2023-11-30 13:16:50 26 4
gpt4 key购买 nike

我有一个按“步骤”更新的游戏网格(Conway 的人生游戏,尽管这与我的问题没有特别关系)。我正在尝试创建一个自动运行模拟的播放按钮,直到再次按下该按钮以暂停模拟。起初我有这样的事情:

public partial class MainWindow : Window
{
bool running = true;
public MainWindow()
{
InitializeComponent();
bool isProgramRunning = true;
while(isProgramRunning)
{
while(running)
ProcessGeneration();
}
}
}

我播放/暂停模拟的按钮具有以下点击处理程序:

private void PlayClick_Handler(object sender, RoutedEventArgs e)
{
PlayButton.Content = ((string)PlayButton.Content == "Play") ? "Pause" : "Play";

running = (running) ? false : true;
}

我认为这会让我的程序简单地继续循环(isProgramRunning 永远不会结束)反复检查“正在运行”是真还是假,按下按钮切换“正在运行”将允许我循环/中断环形。但只是 while(isProgramRunning) 部分终止了程序(它甚至不会加载)。实际上,每次我尝试使用 while() 时,程序都会停止响应。有办法解决这个问题吗?

最佳答案

您可能不希望您的 ProcessGeneration() 尽可能快地发生,屏幕上的所有内容都会变得模糊。此外,您不想阻塞 UI 线程。用一 block 石头杀死两只鸟是可能的,Timer .

创建一个计时器,让它每 1/4 秒运行一次,或者您希望它更新的频率。然后在您的启动和停止代码中,您只需启用或禁用计时器。

public partial class MainWindow : Window
{
private readonly System.Timers.Timer _timer;

public MainWindow()
{
InitializeComponent();

_timer = new Timer(250); //Updates every quarter second.
_timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
}

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
ProcessGeneration();
}

private void PlayClick_Handler(object sender, RoutedEventArgs e)
{
var enabled = _timer.Enabled;
if(enabled)
{
PlayButton.Content = "Play";
_timer.Enabled = false;
}
else
{
PlayButton.Content = "Pause";
_timer.Enabled = true;
}
}

}

关于c# - 在不中断程序的情况下创建无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21694435/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com