【发布时间】:2021-11-30 13:26:31
【问题描述】:
我想使用SerialPort.ReadLine() 读取串行端口上的数据正好 5 秒,然后停止读取。目前我正在使用此代码:
Task t = Task.Run(() => { ReadSerial(); }); // this is the function that reads from serial port
TimeSpan ts = TimeSpan.FromMilliseconds(5000); // I set the timeout period here. Like 5 seconds
if (!t.Wait(ts)) // After 5 seconds, this runs
{
port.Close();
WriteToFile();
t.Dispose();
}
现在,当执行一次时,它工作得非常好。但是如果我在同一个程序中再次执行它,它永远不会离开Task t = Task.Run(() => { ReadSerial(); }); 行。
所以我想知道这是否是做我想做的事情的好方法,我在这里做错了什么?或者是否有更好的方法?
【问题讨论】:
-
“但如果我再执行一次”——“它”是什么?
-
我的问题中提到的整个代码块。那就是“它”。