【发布时间】:2018-04-18 10:14:50
【问题描述】:
我在 Visual Studio 2015 中创建了一个 UI。从 UI 创建的头文件中,我创建了几个线程。在这个线程中,我在一个类中调用一个外部方法。然后,通过这种方法,我想打印结果并将它们添加到 UI 中的列表框中。
但是,它不起作用。我试过Delegate,但也没有用。
在 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 类 (.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);
}
然后,我将gui.h 中的FACE::gui::textLog 更改为public: static
我还阅读了有关检查 textLog->InvokeRequired 的内容,但我没有使用 Delegate。
【问题讨论】:
-
不允许从外部启动的单独线程访问 UI,您需要从 UI 启动线程并且可能需要使用调度程序。
-
谢谢@SchLx,但我在这里找到了解决方案 [link] (msdn.microsoft.com/en-us/library/zyzhdc6b(v=vs.110).aspx)
-
在更简单的情况下它会起作用,如果你得到错误:“调用线程无法访问这个对象,因为不同的线程拥有它。”,尝试使用调度程序,这篇文章也告诉了同样的@ 987654324@.
标签: multithreading visual-studio c++-cli