Answered by:
how to create multi thread in c++/cli windows form

Question
-
Hi, i have created windows form in c++/cli. In my form i used listbox, textbox and button. so when i press button following function should execute....
but am getting cross thread error.... please give me a solution
error:
HResult=0x80131509
Message=Cross-thread operation not valid: Control 'listBox1' accessed from a thread other than the thread it was created on.///program///
public: void print_notification()
{
this->listBox1->Items->Add(this->textBox1->Text);
}
public: void print_output()
{
this->listBox2->Items->Add(this->textBox1->Text);
}private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
ThreadStart^ ThreadMethod1 = gcnew ThreadStart(this, &MyForm::print_notification);
ThreadStart^ ThreadMethod2 = gcnew ThreadStart(this, &MyForm::print_output);
Thread^ MyThread1 = gcnew Thread(ThreadMethod1);
Thread^ MyThread2 = gcnew Thread(ThreadMethod2);
MyThread1->Start();
MyThread2->Start();}
Wednesday, March 18, 2020 12:57 PM
Answers
-
Try this:
void Add1( )
{
listBox1->Items->Add( textBox1->Text );
}
void print_notification( )
{
Invoke( gcnew System::Action( this, &MyForm::Add1 ) );
}
I.e. use Invoke (or BeginInvoke sometimes) to access the controls from threads.
Adjust the second thread too.
- Edited by Viorel_MVP Wednesday, March 18, 2020 2:58 PM
- Proposed as answer by EckiS Wednesday, March 18, 2020 5:07 PM
- Marked as answer by rashmi v Thursday, March 19, 2020 4:43 AM
Wednesday, March 18, 2020 2:38 PM
All replies
-
Try this:
void Add1( )
{
listBox1->Items->Add( textBox1->Text );
}
void print_notification( )
{
Invoke( gcnew System::Action( this, &MyForm::Add1 ) );
}
I.e. use Invoke (or BeginInvoke sometimes) to access the controls from threads.
Adjust the second thread too.
- Edited by Viorel_MVP Wednesday, March 18, 2020 2:58 PM
- Proposed as answer by EckiS Wednesday, March 18, 2020 5:07 PM
- Marked as answer by rashmi v Thursday, March 19, 2020 4:43 AM
Wednesday, March 18, 2020 2:38 PM -
Thank you...its working and how can i set priorities to these threads???
- Edited by rashmi v Thursday, March 19, 2020 6:03 AM
Thursday, March 19, 2020 4:34 AM -
[...] how can i set priorities to these threads???
Try something like this:
MyThread1->Priority = ThreadPriority::Lowest;
Or, inside thread procedure:
Thread::CurrentThread->Priority = ThreadPriority::Lowest;
- Edited by Viorel_MVP Thursday, March 19, 2020 9:46 AM
Thursday, March 19, 2020 9:34 AM