【问题标题】:I am having trouble to utilize a WindowsForms method in a different thread (C++)我无法在不同的线程(C++)中使用 WindowsForms 方法
【发布时间】:2020-12-10 04:37:17
【问题描述】:

对不起我的英语,如果有不清楚的地方,请问我。我无法为 WindowsForms 制作该应用程序(“ThreadTeste”是“MyForm1”的表示):

#include <chrono>
#include <iostream>
#include <thread>

using namespace  std;
using namespace std::chrono;

class ThreadTeste
{
    public:
    void loop()
    {
        for(int i = 0 ; i < 5 ; i++)
        {
            cout << i << endl;
            this_thread::sleep_for(seconds(1));
        }
    }
    thread getThread()
    {
        return thread(&ThreadTeste::loop, this);
    }
    
    ThreadTeste()
    {
        thread myThread = getThread();
        myThread.detach();
    }
 
};

int main(int argc, char *argv[])
{
  
    ThreadTeste* t = new ThreadTeste();
    while(true)
    {
        cout << "Working" << endl;
        this_thread::sleep_for(seconds(1));
    }
} 
//That works!!

D:

【问题讨论】:

  • 那么您的问题到底是什么?你有什么烦恼?
  • WinForms 是一种 C# 技术。它不能在 C++ 中使用。它可以在 C++/CLI 中使用。我们没有看到任何确认您正在使用 C++/CLI 工作的代码,所以这个问题有点令人困惑。
  • 你能告诉我你想做什么,你的问题是什么?从而帮助解决问题。

标签: c++ .net visual-studio winforms console


【解决方案1】:

如果你想从 0 输出到 4,然后输出working,那么你不能使用detach。因为detach的意思是主线程不需要等待子线程的执行完成,而且两者没有关系,所以它会自己运行。

你可以使用join

ThreadTeste()
    {
        thread myThread = getThread();
        myThread.join();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-21
    • 2018-07-14
    • 1970-01-01
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多