Visual C++ (CLI) Threading
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) {
i开发者_开发百科nt 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 _txt
in 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 the Text
property or call AppendText
. To marshal a delegate onto the UI thread use _text->Invoke
.
If Form1::calculate()
is non-static you need to provide the object that the function should be run on, probably this
in your case. You will also run into problems that calculate
takes an argument - the ThreadStart
delegate does is a parameter-less one.
There is an example in MSDN documentation for ThreadStart
that is probably worth looking at.
This is the sample code from MSDN for a non-static ThreadStart
delegate:
Work^ w = gcnew Work;
w->Data = 42;
ThreadStart^ threadDelegate = gcnew ThreadStart( w, &Work::DoMoreWork );
Thread^ newThread = gcnew Thread( threadDelegate );
newThread->Start();
精彩评论