子线程没有返回主线程

时间:2014-02-26 09:07:06

标签: 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;

    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");    
}

它显示消息“outside while”但没有返回主线程。我在哪里显示“我在主线”。我是线程编程的新手,感谢任何帮助

4 个答案:

答案 0 :(得分:0)

在线程启动后添加oThread.Join()

答案 1 :(得分:0)

请检查您是否使用“volatile”关键字来声明rational_status变量,如下所示:

 volatile bool understand_status = true;

还尝试使用Thread.Sleep(1)的Join方法,如下所示:

 oThread.Join();  

答案 2 :(得分:0)

启动异步启动某些工作的线程。你的主线程继续它的工作,但是当检查understand_status时,另一个线程还没有到达你已经改变状态的点,因此你的if子句不符合,因此没有显示任何内容。 / p>

答案 3 :(得分:0)

当主线程进入

if (false == understand_status)
{
     MessageBox.Show("i am in main thread");
}

'understand_status'实际上是真的,因为另一个线程仍在处理中。这是一个简单的竞争条件。

相关问题