0

I created an UI in Visual Studio 2015. From the header file created from the UI, I create several threads. In this threads I call an external method within a class. Then, from this method I would like to print results adding them to a listbox that is in the UI. However, it is not working. I tried with Delegate, but it did not work either.

Creation of threads in gui.h:

FaceCheck^ f1 = gcnew FaceCheck("hello");
System::Threading::Thread^ t1 = gcnew System::Threading::Thread(gcnew System::Threading::ThreadStart(f1, &FaceCheck::WriteText));
t1->Start();

FaceCheck^ f2 = gcnew FaceCheck("goodnight");
System::Threading::Thread^ t2 = gcnew System::Threading::Thread(gcnew System::Threading::ThreadStart(f2, &FaceCheck::WriteText));
t2->Start();

FaceCheck class (.cpp):

#include "FaceCheck.h"
#include "gui.h"

FaceCheck::FaceCheck(System::String^ text_out)
{
    text = text_out;
}
void FaceCheck::WriteText()
{
    FACE::gui::textLog->Items->Add(text);
}

And then, I changed FACE::gui::textLog in gui.h to public: static

I also read about checking if textLog->InvokeRequired, but I did not get to use Delegate.

Ron
  • 14,674
  • 4
  • 34
  • 47
Pablo
  • 463
  • 1
  • 5
  • 12
  • 1
    You are not allowed to access the UI from a separate thread started outside, you need to start the thread from the UI and you might need to use dispatcher. – minus one Apr 18 '18 at 13:50
  • Please, try to clarify your question. The answer here shows how to access the UI from separate thread (started from UI thread): [link](https://stackoverflow.com/questions/1284017/how-to-access-c-sharp-wpf-control-in-thread-safe-way). But it is still tricky since lambda is not available for c++-cli yet. [link](https://stackoverflow.com/questions/45224526/what-is-the-alternative-to-futures-and-promises-in-managed-c/45249490#45249490) – minus one Apr 18 '18 at 14:00
  • Thank you @SchLx, but I found the solution here [link] (https://msdn.microsoft.com/en-us/library/zyzhdc6b(v=vs.110).aspx) – Pablo Apr 19 '18 at 08:49
  • On simpler case it will work, if you get the error: "The calling thread cannot access this object because a different thread owns it.", try to use dispatcher, this post also telling the same [here](https://stackoverflow.com/questions/9732709/the-calling-thread-cannot-access-this-object-because-a-different-thread-owns-it). – minus one Apr 19 '18 at 16:49

1 Answers1

0

I found how to solve it here [link] (https://msdn.microsoft.com/en-us/library/zyzhdc6b(v=vs.110).aspx)

Pablo
  • 463
  • 1
  • 5
  • 12