Well I have this code in my Managed C++/Cli in Visual Studio 2008, I want to be able to access the windows forms items inside of the callback of the Thread Function, and I can’t, it generates an error.
Is there another way to do that? to be able to modify the GUI stuff inside of a method of the WinForms Class by using the Thread function callback ?
This example shows what I want to do.
I need to use a thread because I want to have the other things in the Forms to be accessible, and without using threads everything just freezes until everything is done, and the “Login” function it calls, takes some time because it does HTTP Requests. and after this HTTP Request I set the values that I got from it in a Form Element.
void Login(){
this->btn_next->Enabled = false;
this->login_accounts_facebook->Enabled = false; //This gives an error probably because of accessing "this->"
if(this->clb_contas->CheckedItems->Count <= 0){
//...
}
}
System::Void test_login_Click(System::Object^ sender, System::EventArgs^ e) {
ThreadStart^ start = gcnew ThreadStart(this, &Login_Test::Login);
Thread^ t = gcnew Thread(start);
t->Start();
}
Does anybody know how could I do that? if you think this can’t be done and you want to suggest something something to make the GUI available while doing the process, I’m open for suggestions.
I hope I was being clear enough.
Thanks in advance.
All UI related code should be executed on the UI thread. In your case, that means that only the code you denoted with
//...should be run on a separate thread. Extract that long-running code in its own method and pass that method toThreadStartinstead ofLogin(). Then you’ll need to arrange for a way for the worker thread to notify the UI thread if and when it’s complete.Update:
Here’s a crude example of how to modify your code. I would prefer to extract the long running operation in its own class if it is of sufficient complexity, but I think you get the idea.
The call to
BeginInvokeensures thatLongRunningOperationCompletewill be executed on the form’s UI thread. You can use the same approach to call other methods that update the UI to indicate progress, even while the time-consuming operation is still running. If those methods require more parameters, you can create different delegates with the appropriate signature, and pass those parameters in the call toBeginInvoke. See here for how to do that.