我有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很新
Downvoter請注意評論downvoting的原因。 –
@Lew:我有關於這個問題的搜索,但沒有得到你給的鏈接。非常感謝你的鏈接 –