【问题标题】:.NET Execute a method for fixed 5 seconds and then stop.NET 执行一个方法固定 5 秒然后停止
【发布时间】: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(); }); 行。

所以我想知道这是否是做我想做的事情的好方法,我在这里做错了什么?或者是否有更好的方法?

【问题讨论】:

  • “但如果我再执行一次”——“它”是什么?
  • 我的问题中提到的整个代码块。那就是“它”。

标签: c# .net task


【解决方案1】:

文档声明By default, the ReadLine method will block until a line is received. 我的猜测是您第一次读取所有数据或换行时永远不会收到。阻塞调用永远不会返回,所以你被卡住了。

尝试设置ReadTimeout 并处理异常,而不是尝试自己的超时。

https://docs.microsoft.com/en-us/dotnet/api/system.io.ports.serialport.readline?view=dotnet-plat-ext-6.0

【讨论】:

  • 我将超时设置为(合理?)100 毫秒。但它仍然停留在那个确切的功能上。这很奇怪,因为我知道它正在从另一端接收数据。即使我暂停它,它也会显示放置在我分配给它的变量中的数据。
  • 文档说If a SerialPort object becomes blocked during a read operation, do not abort the thread. Instead, either close the base stream or dispose of the SerialPort object. 没有看到更多代码,我假设ReadLine 方法被阻塞。 Task 类共享一个线程池来管理它们的活动,因此它可以在那里被阻塞。我会尝试处理端口并查看读取是否再次有效(第二次)或使用真正的Thread 并以这种方式启动进程(继续之前的ReadTimeout 实现)。
猜你喜欢
  • 2015-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多