【问题标题】:How to Link SerialPort Received Data to the Main UI thread's Read Function?如何将 SerialPort 接收到的数据链接到主 UI 线程的读取函数?
【发布时间】:2011-08-23 02:01:39
【问题描述】:

我想知道如何将通过串行端口接收到的数据链接到在主 UI 中调用它的函数。

我希望 UI 从串口发送数据,然后暂停线程或等到通过串口线程接收到数据,然后再继续主 UI 线程。

有人告诉我thread.suspend()不是一个安全的函数,我和thread.resume一起尝试过,但是失败了。

我应该查看锁/互斥锁吗?

还是 EventWaitHandles?

我彻底糊涂了!我不熟悉线程,所以任何帮助将不胜感激!谢谢。

代码如下:

public static int SerialCOM_Read(uint tRegisterAddress, out byte[] tRegisterValue, uint nBytes) {

      int retVal = 1;

      tRegisterValue = new byte[nBytes]; 

     byte[] nBytesArray = new byte[4];

        NBytes = nBytes; 


        try {

            ReadFunction = true; 
            YetToReceiveReadData = true; 
        byte[] registerAddress = BitConverter.GetBytes(tRegisterAddress);

        int noOfBytesForRegAdd = 1;

        if (registerAddress[3] > 0) noOfBytesForRegAdd = 4;
        else if (registerAddress[2] > 0) noOfBytesForRegAdd = 3;
        else if (registerAddress[1] > 0) noOfBytesForRegAdd = 2;

        nBytesArray = BitConverter.GetBytes(nBytes);
        {

         Append_Start();
         Append_Operation_with_NoOfBytesForRegAdd(OPERATION.I2C_READ, noOfBytesForRegAdd);
         Append_RegAdd(noOfBytesForRegAdd, tRegisterAddress);
      Append_NoOfBytesOfData(nBytesArray); 

        Send_DataToWrite();

     //Need to Suspend Thread here and Continue once the 
     //ReadData[i] global variable has been assigned.

     for(int i=0; i<nBytes; i++)
tRegisterValue[i] = ReadData[i]; 
     }
         catch(Exception ex) {}

         return retVal;

}

【问题讨论】:

  • 您的代码甚至无法编译,您的 catch 块在 inside 您的 try 块中,这是无效的语法。
  • 您是在编写 WPF 还是 WinForms UI?在任何一种情况下,出于任何原因暂停 UI 线程似乎都是一个坏主意。听起来您正试图在应用程序上强制执行“半双工”通信模式,串行端口客户端应用程序通常不需要这种模式。这是link,无论如何可能会有所帮助。
  • 对不起,它是无效的语法,我错误地剪切和粘贴了我的代码,错过了一个}。我正在使用 Windows 窗体 GUI,感谢您的链接! :)
  • 这看起来已回答,请关闭您的问题。帮助您解决问题的帖子旁边的大复选标记。

标签: c# thread-safety serial-port


【解决方案1】:

如果您要阻塞 UI 线程,那么使用 DataReceived 事件是没有意义的。只需直接调用 SerialPort.Read/Line()。这可能导致用户界面响应的延迟通常是不可取的,但它肯定更容易开始。

【讨论】:

    【解决方案2】:

    只需创建一个委托并使用它将数据发送到可以处理从串行端口接收的数据的方法。我的用例是我通过端口发送数据,但我不知道什么时候会收到响应,可能是任何时候,但那时数据来了,我应该能够获取并处理它,所以我执行以下操作.想想这就是你可能想要的

    Public Delegate Sub recieveDelegate() 
    
    Private Sub datareceived1(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPrt.DataReceived
    
        buffer = buffer & SerialPrt.ReadExisting()
    
        If InStr(1, rxbuff, EOF) > 0 Then
            Rxstring = rxbuff
            rxbuff = ""
            BeginInvoke(New recieveDelegate(AddressOf recieveHandlingMethod), New Object() {})
        End If
    End Sub
    

    只需在接收处理方法中处理您收到的数据。

    【讨论】:

    • 谢谢swordfish,我不确定如何创建一个委托,所以这个信息也很有帮助! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    • 2019-03-14
    • 2014-06-28
    • 2020-09-13
    • 2019-02-20
    相关资源
    最近更新 更多