Simple C# question!

C, C++, Visual C++, C++.Net Topics
Post Reply
User avatar
Trebor29
Lieutenant
Lieutenant
Posts: 75
Joined: Thu Apr 29, 2010 12:34 am

Simple C# question!

Post by Trebor29 » Tue Jun 21, 2011 9:39 pm

(How / Why does the code re-enter the timer1_Tick() method? "It's not in a loop!" )

Hi All,
I was just wondering if someone could explain to me how / why the code re-enters the timer1_Tick() method when counting down.

timeLeft = 30... It checks to see if timeLeft is greater than 0, OK... timeLeft = timeLeft minus 1,,, and then displays the new timeLeft value (29), OK...... I understand up to here!

Stepping through the code, it then jumps to the closing curly bracket of the timer1_Tick() method.... but then re-enters the method to repeat the process, which I know is what we want but why / how is it doing this if its not in a loop?

I would expect it to exit the method and only re-enter after being called again! :?:

Thanks guys! :roll:

P.S. FYI Its the last method!

Code: Select all

namespace Math_Quiz
{
    public partial class Form1 : Form
    {
        // Create a ramdom object to genterate random numbers.
        Random randomizer = new Random();

        // These ints will store the numbers for
        // the adition problem
        int addend1; 
        int addend2;

        // This int will keep track of the time left.
        int timeLeft;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Start the quiz by filling in all the problems 
        /// and starting the timer.
        /// </summary>
        private void startTheQuiz()
        {
            // Fill in the addition problems.
            addend1 = randomizer.Next(51);
            addend2 = randomizer.Next(51);

            plusLeftLabel.Text = addend1.ToString();
            plusRightLabel.Text = addend2.ToString();

            sum.Value = 0;

            //Start the timer
            timeLeft = 30;
            timeLabel.Text = "30 seconds";
            timer1.Start();
        }

        private void startButton_Click(object sender, EventArgs e)
        {
            startTheQuiz();
            startButton.Enabled = false;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (timeLeft > 0)
            {
                // Display the new time left
                // by updating the timeLeft label.
                timeLeft = timeLeft - 1;
                timeLabel.Text = timeLeft + " seconds";
            }
            else
            {
                // If the user runs out of time, stop the timer, show
                // a MessageBox, and fill in the answer.
                timer1.Stop();
                timeLabel.Text = "Time's up!";
                MessageBox.Show("You didn't finish in time.", "Sorry");
                sum.Value = addend1 + addend2;
                startButton.Enabled = true;
            }
        }
    }
}

User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

Re: Simple C# question!

Post by Neo » Tue Jun 21, 2011 10:14 pm

Hey Trebor, Long time no see buddy. I remembered you number of times. I wanted to ask whether you are doing okay or not. We have made a Facebook group as well at http://www.facebook.com/home.php?sk=group_176339872330. Please join with that and add all your friends. So interesting people will join us.


Now lets discuss your question.

These needs to be explained with a little background knowledge about Multi-threading.

A thread is a sequence of instructions executed within the context of a process. Multi-threading is achieved when a program uses multiple execution threads allowing each thread to share the CPU concurrently depending on the priority assigned to these threads. This helps in the optimum usage of System Resources.

The System.Threading namespace provides classes and interfaces that enable multi-threaded programming. This namespace includes a ThreadPool class that manages groups of threads, a Timer class that enables a delegate to be called after a specified amount of time, and a Mutex class for synchronizing mutually-exclusive threads. I also provides classes for thread scheduling, wait notification, and deadlock resolution.

You can create a timer at design-time by dragging and dropping a Timer component from Toolbox to a Form. After that, you can use F4 or right click Properties menu to set a Timer properties as shown in Figure 1. As you can see in Figure 1, the Enabled property is false and Interval is set to 1000 milliseconds (1 second).
timer.jpg
timer.jpg (20.77 KiB) Viewed 4109 times
When you assign 1000 msec as in the picture, this function is called every 1 second using a different thread without disturbing the current execution point of your program.

Think you are in a single core environment (It is easy to understand in this way). Say that you are running a function and you are in the middle of it... And 1 second is gone after the last call to Timer_tick... Then what happen is, the execution of the current function will be kept on hold and the CPU will start executing Timer_tick. After completion, the CPU will continue to execute the function which is on hold.

When you are in multi-core environment, processes/threads can be assigned to each core to execute simultaneously.
User avatar
Trebor29
Lieutenant
Lieutenant
Posts: 75
Joined: Thu Apr 29, 2010 12:34 am

Re: Simple C# question!

Post by Trebor29 » Tue Jun 21, 2011 11:55 pm

:shock: I just wrote a long reply and when I pressed send It had logged me out and I lost the message!!! :( You need to tweek that Neo so that if a user (me) presses send and has been logged out, and the user logs straight back in the message is still sent!

Hi Neo, Im good thank you... How are you?

Ive just finished my second year of my computer science degree, one more year to go! :D Im just playing about with some tutorials trying to keep it fresh in my head and continue with the learning... :lol:

Thanks for getting back to me so quick... WOW! that is some cool stuff you've explained there Neo. The first bit was quite complicated to get my head round but When you talk about single core environments, I have got the gist there. I can see there is some powerful stuff going on here, but my novice mind hasn't got a clue where / how it would be used else where other than this timer. But i am excited about the fact that hopfully one day I will..! :D

Think i'll not worry about multi-core environments for now! :lol:

Thanks again Neo.
Post Reply

Return to “C/C++ Programming”