0

I have a managed c++ application that I start a new thread to do some stuff and update some text boxes, it loops and sleeps at the end of every loop. Because of it sleeping I needed to have it in a new thread so the UI doesn't crash. Then I realized I need to invoke the thread that created the UI to access the textboxes, but now I'm back in the main thread so the sleeping crashes it. How should I approach this.

private: System::Void buttonStartCamera_Click(System::Object^  sender, System::EventArgs^  e) 
         {
             ThreadStart^ threadStart = gcnew ThreadStart(this, &UserInterface::SetText);
             Thread^ newThread = gcnew Thread(threadStart);
             newThread->Start();
         }



    void SetText()
    {
        if (this->textBoxCameraOneX->InvokeRequired)
        {
            MyDel^ del = gcnew MyDel(this, &UserInterface::SetText);
            this->Invoke(del);
        }
        else 
        {
            int count  = 0;
            srand (time(NULL));

            for (count = 0; count < 20; ++count)
            {
                for each (Camera^ camera in cameraList)
                {
                    textBoxCameraOneX->Text = count.ToString();

                }

                Sleep(300);
            }
        }
    }

1 Answers1

0

The best option is likely to refactor this so your Sleep doesn't occur within the SetText method. Your background thread could use a separate method that performs the sleep, and then invokes the proper method to set the text (for one text box at a time) in a loop.

In general, you should keep the methods you use with Control::Invoke as short as possible - they should only include the logic required for your UI work, and not the other functionality.

That being said, in this case, it seems like a System::Windows::Forms::Timer would be more appropriate. You could set the interval to 300, and update a text box one at a time in the timer's Tick event.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373