2016-08-12 3 views
-3

私は別々のスレッドで実行している1つの長時間実行中のプロセスを持っており、この長時間実行中のプロセスが進行しているときに、を表示したい 私のフォームコントロールは、プロセスが進行中であり、ユーザーがプログラムが固まっているかブロックしていると思っていないことを示すだけです。 start or stoppedラベルコントロールに値を代入しようとすると、クロススレッド操作エラーが発生する

は、だから私のフォームコントロールに私はtimer/stop watch以下意志start when my long running method will be calledのようなユーザを表示したいと私は法とすぐに実行し続けるだろう形式下記のフォームにタイマーを表示したいです営業時間:分:秒

コード:

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; 

誰がこれで私を助けることができる私はWinフォーム

+0

Downvoter downvotingの理由をコメントしてください。 –

+0

@Lew:私はこの問題に関して検索しましたが、あなたが与えたリンクはありませんでした。リンクのためにとてもありがとうございます –

答えて

2

にはかなり新しいですので、あなたが正しい必要な呼び出しのためにテストした、あなただけのエラーの原因となっている行を移動する必要がありますifのelse部分にはまだ実行されているので、起動する必要はないはずです。

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のタイマーコントロールを使用しています。イベントdoenst火災。これは同じスレッドの操作のような問題ですか? –

+0

これは多くの変数に依存しますが、あまり参考にすることができません。あなたの元の質問を更新するか、新しいものを投稿してください。 – jbmintjb

2

Control.BeginInvokeコール、ない'name'文字列の割り当てにlblTimer.Textを代入文を入れてください。

関連する問題