有效地检查SerialPort状态

时间:2017-03-31 15:41:36

标签: c# serial-port task

我使用SerialPort并且必须对其状态作出反应(有端口数据读取的自定义指示符)。 我创造了这种结构:

this.connectionWatcher = new Task(async () =>
{
    while (!this.cancelReceive.IsCancellationRequested)
    {
        if ((this.port == null || !this.port.IsOpen) && this.machineState.IsConnected)
            this.machineState.IsConnected = false;
        if (this.port != null && this.port.IsOpen && !this.machineState.IsConnected)
            this.machineState.IsConnected = true;

        await Task.Delay(1000);
    }
}, this.cancelReceive.Token);

machineState.IsConnectedproperty的{​​{1}},用于指标。

我有两个问题(相反,两者都可以同时解决,imho):

  1. 当我关闭应用程序的主窗口时,此bool未停止;
  2. 如何更有效地执行此操作,因为Task不是最佳做法,对CPU有很大影响。

0 个答案:

没有答案