2

ユーザーコントロールでスレッドセーフな呼び出しを実行する方法は知っていますが、それらが動的に生成されると、手がかりがありません。それらの配列リスト(リッチテキストボックス)を作成しようとしましたが、その後「パラメーター開始スレッド」デリゲートに問題がありました。ご入力いただきありがとうございます。

    private void SetText(string text)
    {
        // InvokeRequired required compares the thread ID of the 
        // calling thread to the thread ID of the creating thread. 
        // If these threads are different, it returns true. 
        if (this.currentBox.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(SetText);
            this.Invoke( d, new object[] { text } );
        }
        else
        {
            this.currentBox.Text += text;
        }
    }

  // This method is executed on the worker thread and makes 
    // a thread-safe call on the TextBox control. On a specific text box.....
    private void ThreadProcSafe()
    {
        int i = 0;
        while(_stop_threads == false) {
            this.SetText(String.Format("{0}\n", i));

            ++i;
            Thread.Sleep(100);
        }

        this.SetText(String.Format("Thread Time: {0}:{1}:{2}\n", DateTime.Now.TimeOfDay.Hours, DateTime.Now.TimeOfDay.Minutes, DateTime.Now.TimeOfDay.Seconds)); 

    }
4

1 に答える 1

1

問題は、UI コントロールごとに個別のスレッドがありますが、そのウィンドウ フォームは単一のスレッドで動作することです。そのため、別のスレッドから UI コントロールを更新するのは安全ではありません。

おそらく、それらのスレッドから辞書または配列を埋めて、フォームの単一スレッドの下でその配列からの結果を更新することができます。このようにして、更新された値の配列からすべての UI コントロールを同時に更新します。これはスレッド セーフであり、システム リソースの消費が少なくなります。

于 2012-10-11T22:43:33.187 に答える