c#串行端口侦听器
在C#中是否有任何串行端口侦听器,如果串行端口上有任何数据,它将调用我的函数? 我唯一的想法是使用无限循环,类似这样:c#串行端口侦听器,c#,serial-port,C#,Serial Port,在C#中是否有任何串行端口侦听器,如果串行端口上有任何数据,它将调用我的函数? 我唯一的想法是使用无限循环,类似这样: while true if someDataOnSerialPort callmyfunction(serialPortData) ?? 如果存在任何数据,是否有任何处理程序将调用我的函数? 谢谢。是的,可以使用事件通知新数据,并从事件处理程序内部而不是无限循环中调用函数 下面是MSDN中的示例,该示例稍作修改以使用您的函数名 using System
while true
if someDataOnSerialPort
callmyfunction(serialPortData)
??
如果存在任何数据,是否有任何处理程序将调用我的函数?
谢谢。是的,可以使用事件通知新数据,并从事件处理程序内部而不是无限循环中调用函数
下面是MSDN中的示例,该示例稍作修改以使用您的函数名
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)
{
//....
}
}
是的,可以使用事件来通知新数据,并从事件处理程序内部而不是无限循环中调用函数
下面是MSDN中的示例,该示例稍作修改以使用您的函数名
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)
{
//....
}
}
写入控制台是可行的,但在callmyfunction(indata)行中,我得到了一个错误:
非静态字段、方法或属性需要对象引用
如何修复它?@parman woops,忘了在函数声明、更新答案中输入单词static
。写入控制台是可行的,但在callmyfunction(indata)行中,我得到一个错误:非静态字段、方法或属性需要对象引用
如何修复它?@parman woops,忘了在函数声明中添加静态
,更新答案。问题很好。可笑的是它已经关闭了。问得好。可笑的是它已经关闭了。