繁体   English   中英

秒表在Windows窗体应用程序中无法正常工作

[英]stopwatch is not working correctly in windows form application

我有一个附有计时器的表格。 我想在表单上显示stopwatch并每秒更新一些值到数据库。 我使用了一个windows.form计时器来做到这一点。 但是问题是它使我的应用程序非常慢,并且stopwatch无法正确显示时间。 更新需要3-4秒以上的时间。

另外,当我单击另一个按钮时,计时器也会中断。 我需要stopwatch正常工作,并且刻不容缓。 我现在应该怎么办?

代码如下:

public partial class Form2 : Form
{
    Stopwatch sw = new Stopwatch();
    private Timer _timer;
    int count = 0;
    // The last time the timer was started
    private DateTime _startTime = DateTime.MinValue;

    // Time between now and when the timer was started last
    private TimeSpan _currentElapsedTime = TimeSpan.Zero;

    // Time between now and the first time timer was started after a reset
    private TimeSpan _totalElapsedTime = TimeSpan.Zero;

    private TimeSpan timerSinceStartTime = TimeSpan.Zero;

    // Whether or not the timer is currently running
    private bool _timerRunning = false;
    public Form2(String UserName)
    {
        InitializeComponent();
        _timer = new Timer();
        _timer.Interval = 1000;
        _timer.Tick += new EventHandler(timer1_Tick);

        label4.Text = UserName;

    }

    public static class LoginInfo
    {
        public static string UserID;
    }

    private void richTextBox2_TextChanged(object sender, EventArgs e)
    {


    }



    private void button1_Click(object sender, EventArgs e)
    {
        if (!_timerRunning)
        {
            // Set the start time to Now
            _startTime = DateTime.Now;

            // Store the total elapsed time so far
            _totalElapsedTime = _currentElapsedTime;

            _timer.Start();
            _timerRunning = true;
        }
        sw.Start();
        SqlDataReader rd1;
        SqlConnection Con = new SqlConnection("Data Source=69.162.83.242,1232;Initial Catalog=test1;Uid=test;pwd=1234@Test;MultipleActiveResultSets=true;Connect TimeOut=600;");
        //SqlConnection Con = new SqlConnection("Data Source=ADMIN-PC\\YASH;Initial Catalog=test;Integrated Security=True; Connect TimeOut=600");
        Con.Open();
        rd1 = new SqlCommand("Select SName from ExpertChat where email ='" + label4.Text + "'", Con).ExecuteReader();
        rd1.Read();
        string str;
        str = rd1["SName"].ToString();
        rd1.Close();
        string messageMask = "{0} @ {1} : {2}";
        string message = string.Format(messageMask, str, DateTime.Now.ToShortTimeString(), richTextBox2.Text);
        richTextBox1.AppendText(Environment.NewLine + message);
        SqlCommand cmd, cmd1;
        cmd = new SqlCommand("Update Chat set UserInitial=@message where ExpertName ='" + str + "'", Con);
        cmd.Parameters.AddWithValue("@message" ,message); 
        cmd.ExecuteNonQuery();
        cmd1 = new SqlCommand("Update Chat set Updated=1 where ExpertName ='" + str + "'", Con);
        cmd1.ExecuteNonQuery();
        Con.Close();
        richTextBox2.Text = String.Empty;
        richTextBox1.ScrollToCaret();

    }


    private void button3_Click(object sender, EventArgs e)
    {
        sw.Stop();
        _timer.Stop();
        _timerRunning = false;

        // Reset the elapsed time TimeSpan objects
        _totalElapsedTime = TimeSpan.Zero;
        _currentElapsedTime = TimeSpan.Zero;
        label3.Text = _totalElapsedTime.ToString();  
        MessageBox.Show(count.ToString());

        SqlConnection Con = new SqlConnection("Data Source=69.162.83.242,1232;Initial Catalog=test1;Uid=test;pwd=1234@Test;MultipleActiveResultSets=true;Connect TimeOut=600;");
        //SqlConnection Con = new SqlConnection("Data Source=ADMIN-PC\\YASH;Initial Catalog=test;Integrated Security=True; Connect TimeOut=600");
        Con.Open();
        SqlDataReader rd1;
        rd1 = new SqlCommand("Select SName from ExpertChat where email ='" + label4.Text + "'", Con).ExecuteReader();
        rd1.Read();
        string str;
        str = rd1["SName"].ToString();
        rd1.Close();

        SqlDataReader cmd1;
        cmd1 = new SqlCommand("Update Expertchat Set Booked=0 where email='" + label4.Text + "'", Con).ExecuteReader();
        cmd1.Close();
        SqlDataReader cmd2;
        cmd2 = new SqlCommand("Update chat set EndChat=1,ChatTime=" + count + " where ExpertName='" + str + "'", Con).ExecuteReader();
        cmd2.Close();
        count = 0;
        Con.Close();
        this.Close();
    }

    private void pictureBox1_Click(object sender, EventArgs e)
    {

    }

    private void Form2_Load(object sender, EventArgs e)
    {

    }

    private void richTextBox1_TextChanged(object sender, EventArgs e)
    {

    }

    private void richTextBox1_TextChanged_1(object sender, EventArgs e)
    {

    }

    private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
        SqlConnection Con = new SqlConnection("Data Source=69.162.83.242,1232;Initial Catalog=test1;Uid=test;pwd=1234@Test;MultipleActiveResultSets=true;Connect TimeOut=600;");
        //SqlConnection Con = new SqlConnection("Data Source=ADMIN-PC\\YASH;Initial Catalog=test;Integrated Security=True; Connect TimeOut=600");
        Con.Open();
        SqlDataReader rd1;
        rd1 = new SqlCommand("Select SName from ExpertChat where email ='" + label4.Text + "'", Con).ExecuteReader();
        rd1.Read();
        string str;
        str = rd1["SName"].ToString();
        rd1.Close();
        SqlDataReader rd2 = new SqlCommand("Select top 1 UserName from Chat where ExpertName ='" + str + "'", Con).ExecuteReader();
        rd2.Read();
        string str1;
        str1 = rd2["UserName"].ToString();
        LoginInfo.UserID = str1;
        Con.Close();            
        ClientDetails frm = new ClientDetails(LoginInfo.UserID);
        frm.Show();

    }

    private void label3_Click(object sender, EventArgs e)
    {

    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        count = count + 1;

        timerSinceStartTime = new TimeSpan(timerSinceStartTime.Hours, timerSinceStartTime.Minutes, timerSinceStartTime.Seconds + 1);
        // The current elapsed time is the time since the start button was
        // clicked, plus the total time elapsed since the last reset
        _currentElapsedTime = timerSinceStartTime + _totalElapsedTime;

        // These are just two Label controls which display the current 
        // elapsed time and total elapsed time
        SqlDataReader rd1;
        SqlConnection Con = new SqlConnection("Data Source=69.162.83.242,1232;Initial Catalog=test1;Uid=test;pwd=1234@Test;MultipleActiveResultSets=true;Connect TimeOut=600;");
        //SqlConnection Con = new SqlConnection("Data Source=ADMIN-PC\\YASH;Initial Catalog=test;Integrated Security=True; Connect TimeOut=600");
        Con.Open();

        rd1 = new SqlCommand("Select SName from ExpertChat where email ='" + label4.Text + "'", Con).ExecuteReader();
        rd1.Read();
        string str;
        str = rd1["SName"].ToString();
        rd1.Close();
        SqlDataReader rd;
        rd = new SqlCommand("Select top 1 Data,Updated1 from Chat where ExpertName ='" + str + "' order by id desc", Con).ExecuteReader();
        rd.Read();
        string str5;
        int i;
        str5 = rd["Data"].ToString();
        i = Int32.Parse(rd["Updated1"].ToString());
        rd.Close();
        if (i == 1)
        {
            richTextBox1.AppendText(Environment.NewLine + str5);

            SqlCommand cmd1 = new SqlCommand("Update Chat set Updated1=0 where ExpertName ='" + str + "'", Con);
            cmd1.ExecuteNonQuery();

        }
       label3.Text = timerSinceStartTime.ToString();
        // If we're running on the UI thread, we'll get here, and can safely update 
        // the label's text.

        richTextBox1.ScrollToCaret();




    }
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {


    }

    private void button2_Click(object sender, EventArgs e)
    {

    }
    private void button4_Click(object sender, EventArgs e)
    {

    }


        }

}

问题在于,UI线程中执行了长时间运行的数据库操作。 这意味着由于UI线程忙,因此无法触发计时器事件。 解决方案是将长时间运行的操作放在远离UI的其他线程上。

您的数据库代码很慢。 由于您是在UI线程中执行此操作的,因此它会阻塞您的应用程序。 为了实现期望的目标,您必须(至少)做两件事:

  1. 将数据库代码移至后台工作程序任务或其他线程上。

  2. 优化代码。 这个查询这么慢不是很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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