-1

this is my main thread:

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

this is my sub-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");    
}

it is showing message "outside while" but not returning to main thread. where i am showing "i am in main thread". I am new to thread programming any help appreciated

dcastro
  • 66,540
  • 21
  • 145
  • 155
Deepak Rout
  • 11
  • 1
  • 8
  • are you using winforms or wpf – BRAHIM Kamel Feb 26 '14 at 09:08
  • Either your thread takes more than a second to set `understand_status` to `false`, or else `understand_status` is the victim of jitter optimization (in which case marking it `volatile` should make the problem go away, but `volatile` is something you really should not be using at all; read [this](http://stackoverflow.com/questions/72275/when-should-the-volatile-keyword-be-used-in-c)). – Jon Feb 26 '14 at 09:12
  • 1
    Actually, the thread.Sleep(1) would cause the thread to sleep for a millisecond, not a second.. – Martin Milan Feb 26 '14 at 09:23

4 Answers4

0

add oThread.Join() after thread is started

Helic
  • 907
  • 1
  • 10
  • 25
  • 1
    If you are going to start a thread and immediately `Join` it then why bother in the first place? – Jon Feb 26 '14 at 09:13
0

Please check that you use "volatile" keyword for declaration of understand_status variable like this:

 volatile bool understand_status = true;

Also try to use Join method insted of Thread.Sleep(1) like this:

 oThread.Join();  
fastobject
  • 1,372
  • 12
  • 8
0

You start the thread which asynchronously starts some work. Your main thread continues it's work, but when checking understand_status, the other thread has not yet reached the point where you have changed the status, thus your if clause is not met and therefore nothing is shown.

Mario Stoilov
  • 3,411
  • 5
  • 31
  • 51
0

When you main thread gets to

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

'understand_status' is actually true since the other thread is still processing. This is a simple race condition.

Georgi-it
  • 3,676
  • 1
  • 20
  • 23