如何在C#中添加3秒延迟(visual studio 2010)

时间:2013-12-17 15:55:27

标签: c# .net

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        int randumnum1;
        public Form1()
        {           
            InitializeComponent();          
        }
        public int randumnum()
        {
            Random r = new Random();
            int randumnum = r.Next(15, 30);
            return randumnum;
        }

        private void button2_Click(object sender, EventArgs e)
        {
         randumnum1 = randumnum();
         string strrandumnum = randumnum1.ToString();
         label4.Text = strrandumnum;        
         button2.Text = "New Game";       

        }      

        private void button1_Click(object sender, EventArgs e)
        {
            Random r = new Random();
            int computer = r.Next(1, 4);

            String strrandumnum;            
            if (((Convert.ToInt32(textBox1.Text)) < 1) || ((Convert.ToInt32(textBox1.Text)) > 3))
            {
                MessageBox.Show("Invalid input. Remember you can enter numbers between 1 and 3 only", "Error");
                textBox1.Text = "";
            }
            else if  (Convert.ToInt32(textBox1.Text) == 1)
            {   randumnum1 -= 1;
                strrandumnum = randumnum1.ToString();
                label4.Text = strrandumnum;
                textBox1.Text = "";
            }
            else if (Convert.ToInt32(textBox1.Text) == 2)
            {
                randumnum1 -= 2;
                strrandumnum = randumnum1.ToString();
                label4.Text = strrandumnum;
                textBox1.Text = "";
            }
            else if (Convert.ToInt32(textBox1.Text) == 3)
            {
                randumnum1 -= 3;
                strrandumnum = randumnum1.ToString();
                label4.Text = strrandumnum;
                textBox1.Text = "";
            }    
           //I want a 3 second delay right here but nothing seems to work. I tried the
           //thread sleep but it skipped all the other if statements and was messed up.

                randumnum1 -= computer;
                strrandumnum = randumnum1.ToString();
                label4.Text = strrandumnum;
              }

2 个答案:

答案 0 :(得分:3)

你在评论中说你尝试了Thread.Sleep,而你是对的:这将暂停当前正在执行的线程3秒,这意味着你的用户界面将在3秒内停止响应。

您可能会尝试使用System.Windows.Forms.Timer,可以在您想要延迟发生的代码中启动。然后,当您的延迟完成时,它将触发一个事件,您的延迟后代码应该放在事件处理程序中。这样,您的延迟就可以在不影响UI的情况下发生。

答案 1 :(得分:1)

我猜一种方法是Thread.Sleep(3000);。有很多方法可以做你想要的,但根据你提供的代码,这应该足够了。把它放在你想要延迟的地方。