gpt4 book ai didi

c# - 线程和 UI C# 之间的共享变量

转载 作者:可可西里 更新时间:2023-11-01 14:13:55 29 4
gpt4 key购买 nike

我可以在两个线程之间安全地共享这个“状态”对象吗?

    private bool status = false;

private void uiNewThread_bootloaderStartIdSetupAuto()
{
while (status)
;
}

上面是将从下面的 UI 启动的新线程:

    private void uiBtnBootloaderStartIdSetupAuto_Click(object sender, EventArgs e)
{
if (MessageBox.Show("ID will be setup starting from 1 to 16. \n\nAfter pressing 'YES', press the orange button one-by-one on the nodes.\nThe first pressed node will have number 1, the next number 2, and so on... \n\nWhen done, hit DONE button.", "ID setup", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
status = true;
Thread transmitConfig = new Thread(new ThreadStart(uiNewThread_bootloaderStartIdSetupAuto)); //close port in new thread to avoid
transmitConfig.Start();
}
else
{
Log(LogMsgType.Normal, "User cancelled");
status = false;
}
}

最佳答案

编译器或 CPU 进行的缓存或重新排序等优化可能会破坏您的代码。您应该声明字段 volatile 以防止出现这种情况:

private volatile bool status = false;

可能出错的一个例子是,如果两个线程在不同的内核上运行,status 的值可能会被运行轮询线程的内核缓存在 CPU 寄存器中,因此永远不会看到另一个线程更新的值。

尝试在 Release模式下构建您的应用,您应该会看到这种效果。

关于c# - 线程和 UI C# 之间的共享变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11519998/

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