user1261710
user1261710

Reputation: 2639

C# thread-safe calls on dynamically created controls

I know how to perform thread-safe calls on user controls, but when they are dynamically generated I don't have a clue. I tried to make an array list of them (rich text boxes) and I had problems with the 'parameter start thread' delegate after that. You input is much appreciated.

    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)); 

    }

Upvotes: 2

Views: 542

Answers (1)

Zuuum
Zuuum

Reputation: 1485

The problem is, although you have a separate thread for each UI control, that windows form works under a single thread. So, it is not safe updating UI controls from separate threads.

Maybe you may fill up a dictionary or array from those threads and update the results from that array under the Form's single thread. This way, you will be updating all the UI controls same time from the updated array of values.It is thread safe and it consumes less system resources.

Upvotes: 1

Related Questions