gpt4 book ai didi

c# - 根据另一个按钮激活或停用按钮

转载 作者:行者123 更新时间:2023-11-30 17:06:18 26 4
gpt4 key购买 nike

我是 C# 新手。我有两个 button 和两个 label。我想要的是,当我单击 button1 时,它开始 计数并显示在 label1 中。当我按下 button2 时,它会在 button1 下恢复计数并在 button2开始计数并显示在 label2 中。这是我的代码

bool testt = true;
int i = 0;
int j = 0;

private void button1_Click(object sender, EventArgs e)
{
while (testt)
{
label1.Text = i.ToString();
i++;
System.Threading.Thread.Sleep(50);
if (i > 5000)
{
i = 0;
}
}
}

private void button2_Click(object sender, EventArgs e)
{
testt = false;
while (!testt)
{
label2.Text = j.ToString();
j++;
System.Threading.Thread.Sleep(50);
if (j > 5000)
{
i = 0;
}
}
}

这里的问题是当我点击一个按钮时,它不允许我点击另一个按钮。我使用了一个全局变量来检测按下了哪个按钮。但它不起作用。我怎样才能使这项工作?

最佳答案

您在 UI 线程上执行所有这些操作,因此您阻塞了它。您需要让另一个线程执行实际计数,并使用 Control.Invoke 将标签更改委托(delegate)给主线程,以便主线程有时间运行消息泵。您可以使用内置的 BackgroundWorker 或简单地使用 ThreadPoolTaskFactory 创建一个线程。

我已经写了一个简短的示例来说明如何使用 LINQ 和 ThreadPool 来实现这一点,这不是设计方面的最佳方法,但它可以为您提供一个开发适当解决方案的起点

    semaphore = true;
int i = 0;
int j = 0;

private void button1_Click(object sender, EventArgs e)
{
semaphore = true;
ExecuteAsync(()=>
{
while (semaphore)
{
//Dispatch a call to the UI thread to change the label
Invoke((MethodInvoker)(() => ChangeLabel(label1, i.ToString())));
i++;
Thread.Sleep(50);
if (i > 5000)
{
i = 0;
}
}
});
}

//Executes a function on a ThreadPool thread
private void ExecuteAsync(Action action)
{
ThreadPool.QueueUserWorkItem(
obj => action());
}

private void ChangeLabel(Label label, string labelText)
{
label.Text = labelText;
}

private void button2_Click(object sender, EventArgs e)
{
semaphore = false;
ExecuteAsync(() =>
{
while (!semaphore)
{
//Dispatch a call to the UI thread to change the label
Invoke((MethodInvoker)(() => ChangeLabel(label2, j.ToString())));
j++;
Thread.Sleep(50);
if (j > 5000)
{
i = 0;
}
}
});
}

关于c# - 根据另一个按钮激活或停用按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15455104/

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