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

rangers99Asked:
Who is Participating?
 
lazyberezovskyConnect With a Mentor Commented:
Your thread has no loop inside its thread function. So, it executes once and exits.
0
 
tomandCommented:
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)
0
 
lazyberezovskyCommented:
Use a seed to initialize pseudo random generator.
E.g. Random r = new Random(DateTime.Now.Millisecond);
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
rangers99Author Commented:
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.
0
 
Chuck YetterCommented:
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?
0
 
rangers99Author Commented:
The button is disabled when its clicked. So there is only one thread created. Sorry should have mentioned that.
0
 
lazyberezovskyCommented:
Do you reset myVar to default value after exiting button click event handler?
0
 
rangers99Author Commented:
"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.
0
 
rangers99Author Commented:
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
0
 
lazyberezovskyCommented:
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";              

             ...
}

...
}






0
 
rangers99Author Commented:
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();
0
 
rangers99Author Commented:
Sorry "Thread getDirectionThread = new Thread(new ThreadStart(getDirection));"

should be

Thread getNumberThread = new Thread(new ThreadStart(getNumber));
0
 
Chuck YetterCommented:
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.
0
 
rangers99Author Commented:
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.
0
 
Chuck YetterConnect With a Mentor Commented:
Set some breakpoints in the getNumber() code and step through it to see what is happening there.
0
 
rangers99Author Commented:
Do I need a loop in getNumber() so that it keeps looping (until I tell it to stop)
0
 
Chuck YetterConnect With a Mentor Commented:
Yes, if you want it to keep generating characters for 10 seconds.
0
 
lazyberezovskyCommented:
Do something like

while(true)
 myVar = GetNextValue();

inside thread function
0
 
rangers99Author Commented:
Thanks. God Im dumb,
0
 
Chuck YetterCommented:
Like I said, possible logical error :)
0
All Courses

From novice to tech pro — start learning today.