Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在固定时间内读取串行数据的最有效方法_C#_Serial Port - Fatal编程技术网

C# 在固定时间内读取串行数据的最有效方法

C# 在固定时间内读取串行数据的最有效方法,c#,serial-port,C#,Serial Port,我想在一段固定的时间内继续从我的序列号中读取数据。我的代码是从两个不同的想法中提取出来的,正在运行。然而,我想再次检查一下这是否是正确和最好的方法。我现在的代码是: SerialPort sp = new SerialPort("COM11", 57600); try { sp.Open(); Stopwatch timer = new Stopwatch(); timer.Start(); while (timer.Elapsed.TotalSeconds

我想在一段固定的时间内继续从我的序列号中读取数据。我的代码是从两个不同的想法中提取出来的,正在运行。然而,我想再次检查一下这是否是正确和最好的方法。我现在的代码是:

SerialPort sp = new SerialPort("COM11", 57600);

try
{
    sp.Open();

    Stopwatch timer = new Stopwatch();
    timer.Start();
    while (timer.Elapsed.TotalSeconds < 10)
    {
        // do something
    }
    timer.Stop();

    //byte b = (byte)sp.ReadByte();
    //char c = (char)sp.ReadChar();
    //string line = sp.ReadLine();
    string all = sp.ReadExisting();
    //string all2 = sp.ReadExisting();


    //Console.WriteLine(b);
    //Console.WriteLine(c);
    //Console.WriteLine(line);
    //Console.WriteLine(all);
    Console.WriteLine(all);

    sp.Close();

}
SerialPort sp=newserialport(“COM11”,57600);
尝试
{
sp.Open();
秒表计时器=新秒表();
timer.Start();
同时(计时器已用时间.总秒数<10)
{
//做点什么
}
timer.Stop();
//字节b=(字节)sp.ReadByte();
//char c=(char)sp.ReadChar();
//字符串行=sp.ReadLine();
string all=sp.ReadExisting();
//字符串all2=sp.ReadExisting();
//控制台写入线(b);
//控制台写入线(c);
//控制台写入线(行);
//控制台写入线(全部);
控制台写入线(全部);
sp.Close();
}

建议?

如果在windows上不可靠,请不要同步阅读。40年来,我一直在读串口。可靠读取的唯一方法是使用异步方法。@jdwen关于如何正确执行这种不同的方法有什么建议吗?