c++ - 尝试从表单运行线程

标签 c++ visual-studio multithreading serial-port

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

1) 我正在尝试从属于 Visual C++ 窗体的串口读取数据。我想在 InitializeComponent 函数中创建一个线程,但是当我包含启动线程的调用时,我在表单页面上收到此错误:

"Warning 1 Could not find type 'Thread'. Please make sure that the assembly that contains this type is referenced. If this type is a part of your development project, make sure that the project has been successfully built."

2) 线程会运行在静态函数Read中。读取需要解析主窗体中的串口(串口名为arduino), 但它显然无法解决它们:“.ReadLine 的左侧必须有类/结构/union ”

建议?

    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()

关于c++ - 尝试从表单运行线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6335763/

相关文章:

c++ - 键入 glBegin() 后出现 OpenGL 段错误

c++ - 如何转换 std::make_unique 以便我可以使用类中声明的函数?

c++ - 如何制作 std::function 引用

visual-studio - Visual Studio 2015 更新 3 未安装(无错误或反馈)

c# - 如何等待我的线程完成

c# - 流行的 "volatile polled flag"模式坏了吗?

c++ - 为什么我会得到这种输出,因为我知道数组的非初始化整数元素的默认值为 0?

visual-studio - Visual Studio 2015找不到Visual Studio 2010

visual-studio - 如何在解决方案资源管理器中显示References文件夹而不在VB.NET项目中选择 'Show All Files'?

Python 线程化子函数