正在尝试从窗体运行线程

Trying to run a thread from a form

本文关键字:窗体 运行 线程      更新时间:2023-10-16

我对下面的代码有两个相关的问题

1) 我正试图从Visual C++窗体的串行端口读取。我想在InitializeComponent函数中创建一个线程,但当我包含启动线程的调用时,在窗体页面上出现了此错误:

警告1找不到类型"Thread"。请确保引用了包含此类型的程序集。如果此类型是您的开发项目的一部分,请确保该项目已成功生成。

2) 线程将在静态函数Read中运行。Read需要解析主形式中的串行端口(串行端口名为arduino),但它显然无法解决这些问题:"ReadLine的左边必须有类/结构/联合"

建议?

    using namespace System::IO::Ports;
    using namespace System::Threading;
public ref class Form1 : public System::Windows::Forms::Form
{
public:
    Form1(void)
    {
        InitializeComponent();
        //
        //TODO: Add the constructor code here
        //
    }
private: void static Read(void)
    {
       while (1)
       {
          try
          {
              String^ message = arduino.ReadLine();
           //  this->ArduinoOutputTextBox->Text = message;
          }
          catch (TimeoutException ^) { }
        }
    } 
protected:
    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    ~Form1()
    {
        if (components)
        {
            delete components;
        }
    }
private: System::Windows::Forms::Button^  USB_button;
private: System::IO::Ports::SerialPort^  arduino;
private: System::Windows::Forms::TextBox^  ArduinoOutputTextBox;
private: System::ComponentModel::IContainer^  components;
protected: 
private:
    /// <summary>
    /// Required designer variable.
    /// </summary>

     #pragma region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    void InitializeComponent(void)
    {
        Thread^ readThread = gcnew Thread(gcnew ThreadStart(Read));
        this->components = (gcnew System::ComponentModel::Container());
        this->USB_button = (gcnew System::Windows::Forms::Button());
        this->arduino = (gcnew System::IO::Ports::SerialPort(this->components));
        this->ArduinoOutputTextBox = (gcnew System::Windows::Forms::TextBox());
        this->SuspendLayout();

arduino是对对象的引用,而不是实际对象。

你必须写arduino->readLine()