问题
Is in C# any serial port listener, that will call my function if there will be any data on serial port? My only idea is to use infinite loop, something like this:
while true
if someDataOnSerialPort
callmyfunction(serialPortData)
? Any handler that will call my function if there will be any data? Thanks.
回答1:
Yes there is use the DataReceived event to be notified that new data and call your function from inside that event handler instead of inside a infinite loop.
Here is the example from the MSDN modified slightly to use your function names
using System;
using System.IO.Ports;
class PortDataReceived
{
public static void Main()
{
SerialPort mySerialPort = new SerialPort("COM1");
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
mySerialPort.Open();
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
mySerialPort.Close();
}
private static void DataReceivedHandler(
object sender,
SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
//Console.WriteLine("Data Received:");
//Console.Write(indata);
callmyfunction(indata);
}
private static void callmyfunction(string data)
{
//....
}
}
来源:https://stackoverflow.com/questions/29018001/c-sharp-serial-port-listener