How to change the text of a form label that opens in another thread?

I started filling out the form in a new thread, due to some problems with the delay in the GUI (forms become unresponsive). This thread starts when the function (some_function ()) is called. Such as...

/*========some_function=========*/ void some_function() { System::Threading::Thread^ t1; System::Threading::ThreadStart^ ts = gcnew System::Threading::ThreadStart(&ThreadProc); t1 = gcnew System::Threading::Thread(ts); t1->Start(); while(condition) { Form1^ f1=gcnew Form1(); //some coding //to change the values of a different form (Form1) } } /*======ThreadProc=========*/ void ThreadProc() { Form1^ f1=gcnew Form1(); f1->Show(); //OR Application::Run(Form1()); } 

Now the problem is changing the values ​​of the form (Form1), such as label text, progress bar, etc., in the "while" loop. Is there a way to change the values ​​of a form that is open in different threads?

+4
source share
1 answer

Check Control :: Invoke to drop the method into a safe stream to modify the control. To show the form of your example:

 public delegate void SwapControlVisibleDelegate(Control^ target); public ref class Form1 : public System::Windows::Forms::Form { /*Ctor and InitializeComponents for Form1*/ /*...*/ protected : virtual void OnShown(EventArgs^ e) override { __super::OnShown(e); some_function(); } void some_function() { System::Threading::Thread^ t1; System::Threading::ThreadStart^ ts = gcnew ystem::Threading::ThreadStart(this, &Form1::ThreadProc); t1 = gcnew System::Threading::Thread(ts); t1->Start(); } void ThreadProc() { Threading::Thread::Sleep(2000); for each(Control^ c in this->Controls) { SwapVisible(c); } } void SwapVisible(Control^ c) { if(c->InvokeRequired) // If this is not a safe thread... { c->Invoke(gcnew SwapControlVisibleDelegate(this, &Form1::SwapVisible), (Object^)c); }else{ c->Visible ^= true; } } } 

Here's how to invoke a method control in a safe thread to make changes. Right now I read your comment for the question. Take a look at the BackgroundWorker component , it is ideal for running an asynchronous task with cancellation support, and it also implements events to receive notifications about the progress and completion of a task.

0
source

Source: https://habr.com/ru/post/1435635/


All Articles