我可以安全地在兩個線程之間共享此「狀態」對象嗎?線程和UI之間的共享變量C#
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架構和.NET Framework,揮發性或多或少是多餘的。喬達菲在這裏討論。 http://www.bluebytesoftware.com/blog/2010/12/04/SayonaraVolatile.aspx – stevethethread 2012-07-17 09:53:04
@stevethethread:在我的系統中,我無數次地重新創建了這個場景,並在.NET中獲得了一個死鎖。這裏的問題是非常真實的。 – Tudor 2012-07-17 09:55:39
不幸的是,即使通常通過使用'volatile'來正常工作,一個'volatile write'也不能保證在宇宙熱死之前完成寫操作:-) – xanatos 2012-07-17 10:05:59