2012-03-10 140 views
0

我使用System.Windows.Forms.Timer顯示傳輸文件更新進度(的timeleft,速度..等)Timer.Start()僅適用於第一次調用?

,我也用backgroundworker將文件發送

  • backgroundWorker1_DoWork電話timer1.Start();
  • backgroundWorker1_RunWorkerCompleted電話timer1.Stop();

它只在第一次調用timer1.Strat時工作正常,但是當它再次調用後r timer1.Stop()。它不起作用。

timer1.Enabled = True; 
timer1.Interval = 1000; 
private void timer1_Tick(object sender, EventArgs e) 
    { 
     long speed = sumAll - prevSum; 
     prevSum = sumAll; 
     labelSpeed.Text = CnvrtUnit(speed) + "/S"; 
     if (speed > 0) 
     { 
      totalSeconds++; 
      labelTime.Text = FormatRemainingText(TimeSpan.FromSeconds((sizeAll - sumAll)/speed)); 
      labelTotalTime.Text = FormatRemainingText(TimeSpan.FromSeconds(totalSeconds)); 
     } 
    } 

它是怎麼回事,我該如何解決它?

+0

sumAll是什麼定義?你怎麼知道它沒有被召喚。你是否在調試模式下斷點,它從不打? – 2012-03-10 04:07:39

+0

sumAll是sentBytes ..就像[512k]/23340K 不,我沒有說它沒有被調用...它叫但不工作..它給了我也不例外..只是標籤不更新了。 – 2012-03-10 04:16:43

+0

也許如果你讓文字變得更大膽,它會自行解決。 – 2012-03-10 04:17:00

回答

2

我已經想通了,我用的System.Timers.Timer代替System.Windows.Forms.Timer

System.Timers.Timer timer1 = new System.Timers.Timer(1000); 

在類的構造函數我說:

public FileTransfer() 
    { 
     InitializeComponent(); 
     timer1.Elapsed += timer1_Tick; 
    } 


    private void timer1_Tick(object sender, EventArgs e) 
    { 
     long speed = sumAll - prevSum; 
     Console.WriteLine(speed); 
     prevSum = sumAll; 
     Speed(CnvrtUnit(speed) + "/S"); 
     if (speed > 0) 
     { 
      totalSeconds++; 
      Timeleft(FormatRemainingText(TimeSpan.FromSeconds((sizeAll - sumAll)/speed))); 
      TotalTime(FormatRemainingText(TimeSpan.FromSeconds(totalSeconds))); 
     } 
    } 

    private void Timeleft(string value) 
    { 
     if (InvokeRequired) 
     { 
      this.Invoke(new Action<string>(Timeleft), new object[] { value }); 
      return; 
     } 
     labelTime.Text = value; 
    } 
    private void TotalTime(string value) 
    { 
     if (InvokeRequired) 
     { 
      this.Invoke(new Action<string>(TotalTime), new object[] { value }); 
      return; 
     } 
     labelTotalTime.Text = value; 
    } 
    private void Speed(string value) 
    { 
     if (InvokeRequired) 
     { 
      this.Invoke(new Action<string>(Speed), new object[] { value }); 
      return; 
     } 
     labelSpeed.Text = value; 
    } 

現在,它的工作原理每次我打電話timer1.Start()時間,沒必要「自動復位」。