首页 > 解决方案 > [C++,windows窗体]如何让主线程等待被调用线程完成?

问题描述

我创建了 2 个按钮,一个用于启动新线程,另一个用于结束它。新线程内部的实际计算涉及 new[] 和 delete[] 所以我不直接中止线程,而是使用标志来结束它。结束 delete[] 和结果保存可能需要一些时间,所以我希望主线程等待新线程结束。但是无论我怎么尝试,我发现新线程不会运行(尽管它的 ThreadState 正在运行),直到执行停止按钮的命令行。System::Threading::Thread 的工作方式与我的线程完全不同。它应该是怎样的?

#include "stdafx.h"

ref class Form1 : System::Windows::Forms::Form
{
public:
//define a thread name and a flag to terminate the thread
System::Threading::Thread^ th1;
static bool ITP1=0;

Form1(void)
{InitializeComponent();}

System::Windows::Forms::Button^ ButtonStart;
System::Windows::Forms::Button^ ButtonStop;
System::Windows::Forms::Label^ Label1;

void InitializeComponent(void)
{
    this->SuspendLayout();

    this->ButtonStart = gcnew System::Windows::Forms::Button();
    this->ButtonStart->Location = System::Drawing::Point(20, 20);
    this->ButtonStart->Click += gcnew System::EventHandler(this, &Form1::ButtonStart_Click);
    this->Controls->Add(this->ButtonStart);

    this->ButtonStop = gcnew System::Windows::Forms::Button();
    this->ButtonStop->Location = System::Drawing::Point(120, 20);
    this->ButtonStop->Click += gcnew System::EventHandler(this, &Form1::ButtonStop_Click);
    this->Controls->Add(this->ButtonStop);

    this->Label1 = gcnew System::Windows::Forms::Label();
    this->Label1->Location = System::Drawing::Point(20, 80);
    this->Controls->Add(this->Label1);

    this->ResumeLayout(false);
    }

void ThreadStart()
{
    for (int idx=0;idx<999999999;++idx)
    {
        if (ITP1) break;
    }
    this->Label1->Text = "finished";
    ITP1=0;
}

System::Void ButtonStart_Click(System::Object^ sender, System::EventArgs^ e)
{
    th1 = gcnew System::Threading::Thread(gcnew System::Threading::ThreadStart(this,&Form1::ThreadStart));
    th1->Start();
    this->Label1->Text = "running";
}

System::Void ButtonStop_Click(System::Object^ sender, System::EventArgs^ e)
{
    if (th1->ThreadState==System::Threading::ThreadState::Running)
    {
        //use the flag to stop the thread
        ITP1=1;
        //the wait method using while+sleep doesn't work
        while (th1->ThreadState==System::Threading::ThreadState::Running)   System::Threading::Thread::Sleep(1000);
        //replacing the wait method above with "th1->Join()" doesn't work either
    }
}
};

int main()
{
Form1^ A1 = gcnew Form1();
A1->ShowDialog();
return 0;
}

标签: multithreadingc++-cli

解决方案


您必须join()在主线程中调用线程。然后主线程将一直等待,直到被调用的线程完成。

请参阅文档Join以了解如何调用它。


推荐阅读