Link to home
Start Free TrialLog in
Avatar of rangers99
rangers99

asked on

Visual C# - Why does my Thread Execute Only Once?

Hello Dudes

Im developing a Windows application in Visual C# using Visual Studio 2008.

IThe example below is a simplification but explains the principle of whats happening (or not happening). I have a form that has a button.  The code for the main window is myForm.cs. When I click the button I start a thread that sets a variable. The actual code in the button_click event checks the value of that variable.

However my thread only seems to execute once ie. in the code below myVar is only set once when it should be set every time the thread executes.

Any ideas what Im doing wrong?

public partial class ControlWindow : Form {

....
string myVar = "";


private void myButtonB_Click(object sender, EventArgs e) {

Thread getNumberThread = new Thread(new ThreadStart(getNumber));
                                            getNumberThread.Start();

while (myVar != "C")
{
   // ** do some calculations in here **   
   Application.DoEvents();
}

getNumberThread.Abort();

}



protected void getNumber()
{

                Random random = new Random();
                int randomNumber = random.Next(0,5);

                if (randomNumber == 0)
                   myVar = "A";

                if (randomNumber == 1)
                    myVar = "B";

                if (randomNumber == 2)
                    myVar = "C";

                if (randomNumber == 3)
                    myVar = "D";

                if (randomNumber == 4)
                    myVar = "E";
}

...


}

Open in new window

Avatar of tomand
tomand
Flag of Czechia image

Hi,

Are you sure the random() doesn't return the same 'random' value ?

Note: I assume that the thread you created for some educational purpose. I would be better to use a normal routine/function call to the same, IMHO.

You can place some status variables manipulations into the thread to be sure it was executed (increment a int variable or so)
Use a seed to initialize pseudo random generator.
E.g. Random r = new Random(DateTime.Now.Millisecond);
Avatar of rangers99
rangers99

ASKER

Hi
No the random function definetly works.
And I know the example is a bad way of doing things but its just an illustration. My actual application talks to hardware and its time consuming and hence why I want it in another thread.
Every time you click the button you are starting another thread.  In addition to that, every time the button is clicked and myVar is not "C", the event handler loops endlessly waiting for some thread to set myVar to "C".  When you finally get one of the threads to set myVar to "C", all of the event handlers finally close and abort their threads.   I used your code above and myVar indeed had a different value everytime.
Since the code above works, but your actual code doesn't, I would say you have a logical error in your code so that myVar always has the same value.  Maybe you could post the real code?
The button is disabled when its clicked. So there is only one thread created. Sorry should have mentioned that.
Do you reset myVar to default value after exiting button click event handler?
"Do you reset myVar to default value after exiting button click event handler"

Hi, Thats irrelevant since the thread is running within the button click event handler. I abort the thread when I exit the button_clcik event handler.
Axshun,
My actual code is a bit convoluted. I'll post it if all else fails. It certainly looks OK and is behaving in the same way as the example above ie.  the thread is aborting after one execution
If you do not reset myVar value after doing getNumberThread.Abort() then next time you enter this event handler condition while (myVar != "C") will be true (if value will not be re-assigned inside thread function till that moment). And again, you will kill your thread without changing myVar.

Maybe this helps:

public partial class ControlWindow : Form {
....
string myVar = String.Empty;

private void myButtonB_Click(object sender, EventArgs e) {

Thread getNumberThread = new Thread(getNumber);
getNumberThread.Start();

while (myVar != "C")
{
   // ** do some calculations in here **  
   Application.DoEvents();
}

getNumberThread.Abort();
myVar = String.Empty; // reset variable
}

protected void getNumber()
{
                Random random = new Random(DateTime.Now.Millisecond); // initialize generator
                int randomNumber = random.Next(0,5);

                if (randomNumber == 0)
                   myVar = "A";              

             ...
}

...
}






I think the example I gave was a bit confusing. If you replace the while loop with something like the following then you will see myVar never changes.




  Thread getDirectionThread = new Thread(new ThreadStart(getDirection));
   getNumberThread.Start();
 DateTime start = DateTime.Now;
                                         
                                                   
                                                    do {
                                                 
                                                        label1.Text = myVar;
                                                        Application.DoEvents();

                                                    } while (DateTime.Now.Subtract(start).Seconds < 10);   // loop for 10 seconds

 getNumberThread.Abort();
Sorry "Thread getDirectionThread = new Thread(new ThreadStart(getDirection));"

should be

Thread getNumberThread = new Thread(new ThreadStart(getNumber));
I replaced the code with the do/while loop above, and the value did change.  So either your thread is taking longer than 10 seconds to find the value of myVar, or there could be an error in getNumber() that prevents myVar from getting a new value.
Hi Axshun
Yes it changes but surely it should change continuously for 10 seconds until the loop ends. Im wanting the thread to keep running in the background for 10 seconds updating the value of that variable all the time but its just not happening.
SOLUTION
Avatar of Chuck Yetter
Chuck Yetter
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Do I need a loop in getNumber() so that it keeps looping (until I tell it to stop)
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Do something like

while(true)
 myVar = GetNextValue();

inside thread function
Thanks. God Im dumb,
Like I said, possible logical error :)