serialPort_DataReceived事件的问题

时间:2012-06-01 10:09:44

标签: c# events serial-port

我在班级沟通下有一个功能

    public int SerialCommunciation()
    {
        /*Function for opening a serial port with default settings*/
        InitialiseSerialPort();

        /*This section of code will try to write to the COM port*/   
        WriteDataToCOM();

        /*An event handler */                   
       _serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);

       return readData;
    }

下面

     int readData /*is a global variable*/

_serialPortDataRecieved()根据从串口读取的数据更新变量readData

   /* Method that will be called when there is data waiting in the buffer*/
    private void _serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {

       string text = _serialPort.ReadExisting();
       int.TryParse(text, out readData);

    }

现在,当我从另一个类

调用此函数时
   valueReadFromCom=Communication.SerialCommunication()

我需要从串口读取值,但我得到0。 当我尝试调试此代码时,我发现控件首先转到语句

   return readData;

在函数SerialCommunication中,然后控制转到函数_serialPort_DataRecieved,由事件触发的函数。如何使整个过程同步,这意味着只有在执行函数_serial_DataRecieved后才能从函数serialCommunication返回readData。

1 个答案:

答案 0 :(得分:2)

请注意,以下不是串行端口工作异步的正确方法。另一方面,无论如何它都能完成这项任务。

只需添加一个boolen属性并在从SerialCommunication函数返回之前检查此属性;收到数据时将此属性设置为true。

private bool dataReceived = false;   

public int SerialCommunciation()
{
    /*Function for opening a serial port with default settings*/
    InitialiseSerialPort();

    /*This section of code will try to write to the COM port*/
    WriteDataToCOM();

    /*An event handler */
    _serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);

    while (!dataReceived)
    {
        Thread.Sleep(1000);
    }
    return readData;
}

private void _serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
   string text = _serialPort.ReadExisting();
   int.TryParse(text, out readData);
   _serialPort_DataReceived = true;
}