日期:2014-05-20  浏览次数:20786 次

timer计时器问题
下面的代码执行时,timer和for循环怎么不是同步执行呢
private void button3_Click(object sender, EventArgs e)
  {
  timer1.Interval = 50;
  progressBar1.Value = 0;
  timer1.Enabled = true;
  timer1.Start();
   
  for (int i = 0; i < 476; i++)
  {
   
  for (int j = 1; j < 78; j++)
  {
   
  int id = 3888 + i;
  string Station = "Station" + j;
  string sqlselect = "select "+Station+" from BusStationRowG where id="+id;
  SqlCommand comm2 = new SqlCommand(sqlselect, Consql.con);
  Consql.con.Open();
  SqlDataReader reader = comm2.ExecuteReader();
  reader.Read();
  if (reader[0].ToString() =="")
  {
  Consql.con.Close(); 
  }
  else
  {
  Consql.con.Close(); 
  string sql = "Insert into BusStationColumn(BusNo,Station) select BusNo," + Station + " from BusStationRowG where id=" + id;
  try
  {
  SqlCommand comm = new SqlCommand(sql, Consql.con);
  Consql.con.Open();
  comm.ExecuteNonQuery();
  }
  catch (Exception ex)
  {
  MessageBox.Show(ex.Message);
  }
  finally
  {
  Consql.con.Close();
  }
   
  }
   
  }
  }
   

  MessageBox.Show("完成1!");
  }
  private void timer1_Tick(object sender, EventArgs e)
  {
  progressBar1.Value += 1;
  if (progressBar1.Value >= 100)
  {
  timer1.Stop();
  MessageBox.Show("完成2!");
   
  }
  }
我实行边执行往数据库中加数据,滚动条边前进,当数据填完时,滚动条也结束,跳出对话框提示完成,应该怎么改呀,求解!

------解决方案--------------------
因为你只有一个线程在做着事情

这种长时间的处理,不能放在button的时间里,否则会导致界面卡死

应该用异步来做这种事情,如果用了异步,那么进度条的问题就自然而然解决了
C# code

        private void button1_Click(object sender, EventArgs e) {
            new Thread(work).Start();
        }

        private void work()
        {
            for (int i = 0; i < 100; i++)
            {
                // 用sleep替代你的费时的操作
                Thread.Sleep(100);
                // 操作完成之后更新UI
                this.Invoke(new Action(notify));
            }
        }

        private void notify()
        {
            this.progressBar1.Value++;
        }