簡體   English   中英

C#Visual Studio中的多線程並從連接到arduino的串行端口接收數據

[英]Multithreading in C# Visual Studio and receiving data from serialport connected to arduino

誰能告訴我我在做什么錯? 我收到一條錯誤消息,說無法在線程上訪問tbOutput?

我猜這是關於它沒有安全執行的問題。 我該如何解決此錯誤?

    private void DataReceivedHandler(
                object sender,
                SerialDataReceivedEventArgs e)
    {
        this.demoThread = new Thread(new ThreadStart(this.ThreadProcSafe));

        this.demoThread.Start();

        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        tbOutput.Text = indata;
    }

    private void ThreadProcSafe()
    {
        this.SetText("Something happened correctly");
    }

    private void SetText(string text)
    {
        if (this.tbOutput.InvokeRequired)
        {
            SetTextCallBack d = new SetTextCallBack(SetText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            this.tbOutput.Text = text;
        }
    }

由於您的DataReceivedHandler是在非UI線程上調用的,因此您可能會收到錯誤。 如以下所述: https : //msdn.microsoft.com/zh-cn/library/system.io.ports.serialport.datareceivedv = vs.110) .aspx (“備注”部分)

如果使用的是.NET 4,則可以執行以下操作:

tbOutput.Text = indata

你應該做:

tbOutput.Invoke(new Action(() => tbOutput.Text = indata));

而且您不需要額外的線程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM