I am using Visual C++ 2008 with CLI. I have a form with a textbox and a button, once i press the button i want the following code to output as follows:
private:
System::Void button_Click(System::Object^ sender, System::EventArgs^ e) {
Thread ^thr1 = gcnew Thread(gcnew ThreadStart(&Form1::calculate("t1")));
Thread ^thr2 = gcnew Thread(gcnew ThreadStart(&Form1::calculate("t2")));
thr1->Start();
thr2->Start();
}
void calculate(String^ val) {
int j;
for(j=0; j<10; j++)
_txt->AppendText(val + Convert::ToString(j) + "\n");
}
Desired output:
t1 0
t2 0
t1 1
t2 1
etc…
My code above does not work. Stating that i the delegate requires two inputs at the gcnew Thead line. What am i doing wrong? Also is there a better way to achieve this?
I will punt on the compilation error since C++\CLI is not a familar language to me. However, I can mention another problem.
You are attempting to access a UI control from a non-UI thread. You cannot touch
_txtin any way shape or form (even just reading a property) from a worker thread or any other thread except for the main UI thread. What you can do is marshal the execution of a delegate back onto the UI thread and from that you can change theTextproperty or callAppendText. To marshal a delegate onto the UI thread use_text->Invoke.