2016-08-12 32 views
-3

我有1個長時間運行的進程,我在單獨的線程上運行,當這個長時間運行的進程正在進行時,我想顯示像秒錶 我的表單控件只是爲了顯示進程正在進行,用戶不認爲程序卡住或阻塞。嘗試賦值給標籤控制時出現交叉線程操作錯誤

所以在我的表單控件我想顯示用戶timer/stop watch像下面這將start when my long running method will be called,我想顯示在下面的格式形式將繼續爲法儘快運行定時器start or stopped

小時:分鐘:秒

代碼:

private void btnBrowse_Click(object sender, EventArgs e) 
     { 
      this.Invoke(new delegateFileProgress(Progressbarcount), 0); 
      OpenFileDialog openFileDialog = new OpenFileDialog(); 
      DialogResult dialog = openFileDialog.ShowDialog(); 
      if (dialog == DialogResult.OK) 
      { 
       Thread longRunningProcess = new Thread(() => LongRunningMethod(openFileDialog.FileName)); 
      } 
     } 

private void LongRunningMethod(string path) 
     { 
      stopwatch.Start(); 

      TimeSpan ts = stopwatch.Elapsed; 
      string name = string.Format("{0}:{1}", Math.Floor(ts.TotalMinutes), ts.ToString("ss\\.ff")); 
      if (lblTimer.InvokeRequired) 
      { 
       lblTimer.BeginInvoke(new MethodInvoker(delegate { name = string.Format("{0}:{1}", Math.Floor(ts.TotalMinutes), ts.ToString("ss\\.ff")); })); 
      } 

      lblTimer.Text = name; Error:Cross-thread operation not valid: Control 'lblTimer' accessed from a thread other than the thread it was created on. 
      /* 
      * Long running codes which takes 30 - 40 minutes 
      */ 
      stopwatch.Stop(); 
     } 

但是下面一行收到錯誤:

跨線程操作無效:控制「lblTimer」從比它創建的線程以外的 線程訪問。

lblTimer.Text = name; 

任何人可以幫助我,是因爲我在winform很新

+0

Downvoter請注意評論downvoting的原因。 –

+0

@Lew:我有關於這個問題的搜索,但沒有得到你給的鏈接。非常感謝你的鏈接 –

回答

2

你所需的invoke這是正確的測試,你只需要移動,導致該錯誤的行進入if的其他部分,因爲它仍然在運行,如果需要調用,這不應該是。

private void LongRunningMethod(string path) { 
    stopwatch.Start(); 
    TimeSpan ts = stopwatch.Elapsed; 
    string name = string.Format("{0}:{1}", Math.Floor(ts.TotalMinutes), ts.ToString("ss\\.ff")); 
    if (lblTimer.InvokeRequired) { 
    lblTimer.BeginInvoke(new MethodInvoker(delegate { 
     lblTimer.Text = name; 
    })); 
    } else { 
    lblTimer.Text = name; 
    } 
    stopwatch.Stop(); 
} 
+0

這工作正常。當我使用system.windows.forms的計時器控制時,爲什麼計時器打勾事件引發的火災。像跨線程操作一樣的問題? –

+0

這將取決於很多變數,在沒有例子抱歉的情況下無法幫助你。更新您的原始問題,或發佈一個新的,因爲這聽起來像它現在漂移到一些新的東西! – jbmintjb

2

放進了Control.BeginInvoke呼叫時,'name'字符串不是指派指派lblTimer.Text聲明。

相關問題