简体   繁体   中英

how do i print more than one number to a single label

After watching Futurama start to finish for the third or forth time I decided I wanted to try and program up the random number count down generator from episode "A Tale of Two Santas". When I first started this project I only started with displaying one single number at a time, during this step the program appeared to run perfectly. Then I moved onto trying to make my display match the one in the episode with a second delay between each number. After I added code to do this my program doesn't display any number until it hits zero and then closes the program. Instead When I first click my button, it displays "label" for the first second then it cuts it back to "lab" or "la" and half of the letter be until it hits zero. I Have no clues as to why this is happening and would appreciate any input into why this is happening. My code is below.

namespace FuturomaRandomNumberCountDown
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        bool keepRunning = true; //used for loop kickout
        private void start_Click(object sender, EventArgs e)
        {
            while (keepRunning == true)
            {
                Random random = new Random((int)DateTime.Now.Ticks);
                int randomNum = random.Next(0, 99);

                display.Text = Convert.ToString(randomNum);/display number
                Thread.Sleep(1000);//delay

                if(randomNum==0)//check for zero
               { keepRunning = false; }//to kick out of the while loop
            }
            Application.Exit();
        }
    }
}

It has to do with threads and what Thread.Sleep actually does. When you are running your program, all of the GUI-related code runs on the same thread. This is the same thread that runs all your event code, so when you do some processing in event code, your GUI isn't going to update until that code returns.

In your case, you are looping through every value you want to display within the same while loop. This is hogging the main thread of your program, and it's not giving the GUI a chance to update in between every change. Additionally, when you call Thread.Sleep , that pauses whatever is the current thread, which in this case is your main thread. That has the effect of pausing the entire program.

In order to do what you want to do, you're going to have to one of two things. Either use multithreading to put your random number generator on a different thread , or use a Timer object to handle your refreshing .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM