c# - 如何将 SerialPort 接收到的数据链接到主 UI 线程的读取函数?

标签 c# thread-safety serial-port

我想知道如何将通过串行端口接收的数据链接到在主 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;

最佳答案

如果您打算阻塞 UI 线程,那么使用 DataReceived 事件就没有意义了。直接调用 SerialPort.Read/Line() 即可。这可能导致用户界面响应延迟通常是不受欢迎的,但它确实更容易上手。

关于c# - 如何将 SerialPort 接收到的数据链接到主 UI 线程的读取函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7155551/

相关文章:

c# - 想要 C# 程序启动 WPF 应用程序

c# - 不可重置的 "flags"线程在 C#/.NET 中是否安全?

java - 如何在不关闭连接的情况下更改波特率?

c# - INotifyPropertyChanged 不更新 UI(WPF)

c# - 如何通过t4生成自定义类?

java - Varargs、不可变数组和线程安全

java - ImageIO.read 在多线程执行中抛出异常

javascript - 将包含单个整数的数组传递给 Uint8Array 会对传递给它的内容产生什么影响?

c# - 如何确定我们从串口c#接收到所有数据

c# - 无法从 system.collections.generic.list 转换为字符串到 Vba.collections