C# 子线程不返回主线程
这是我的主线:C# 子线程不返回主线程,c#,multithreading,C#,Multithreading,这是我的主线: private void button1_Click(object sender, EventArgs e) { Thread oThread = new Thread(new ThreadStart(understand)); // create the thread for understand function oThread.Start(); // start the thread button1.Enabled = false
private void button1_Click(object sender, EventArgs e)
{
Thread oThread = new Thread(new ThreadStart(understand)); // create the thread for understand function
oThread.Start(); // start the thread
button1.Enabled = false;
Thread.Sleep(1);
if (false == understand_status)
{
MessageBox.Show("i am in main thread");
}
}
这是我的子线程:
private void understand()
{
int license_value=0;
while (understand_status)
{
..............
if (license_value < 29)
{
understand_status = false;
...........
}
if (false == understand_status)
{
MessageBox.Show("inside while");
File.Delete("C:\\log.txt");
}
}
MessageBox.Show("outside while");
}
private void understand()
{
int license_值=0;
while(了解_状态)
{
..............
如果(许可证值<29)
{
理解_状态=错误;
...........
}
if(false==了解_状态)
{
MessageBox.Show(“内部while”);
文件。删除(“C:\\log.txt”);
}
}
MessageBox.Show(“外出时”);
}
它显示消息“outside while”,但不返回主线程。在那里我显示“我在主线程”。我是线程编程新手,欢迎您提供任何帮助在线程启动后添加oThread.Join()请检查您是否使用“volatile”关键字声明了解\u状态变量,如下所示:
volatile bool understand_status = true;
oThread.Join();
还可以尝试使用Join方法代替Thread.Sleep(1),如下所示:
volatile bool understand_status = true;
oThread.Join();
您启动线程,该线程以异步方式启动一些工作。你的主线程继续它的工作,但是当检查
understand_status
时,另一个线程还没有达到你改变状态的点,因此你的if
子句没有满足,因此没有显示任何内容。当你的主线程到达
if (false == understand_status)
{
MessageBox.Show("i am in main thread");
}
“understand_status”实际上是真的,因为另一个线程仍在处理。这是一个简单的争用条件。您使用的是winforms还是WPF?您的线程需要一秒钟以上的时间才能将
understand\u status
设置为false
,否则understand\u status
就是抖动优化的牺牲品(在这种情况下,将其标记为volatile
应该可以解决问题,但是volatile
是您根本不应该使用的东西;请阅读)。实际上,线程。Sleep(1)将导致线程睡眠一毫秒,而不是一秒钟。如果要启动一个线程并立即加入,那么首先为什么要麻烦呢?我的主线程是UI线程如果我要使用加入,我将无法访问UI。