如何取消等待SerialPort.BaseStream.ReadAsync?

时间:2017-03-24 13:37:06

标签: c# .net asynchronous serial-port task

我的c#WinForms应用程序从串口异步读取。它可以工作,但当端口关闭时,会出现StackOverflowException。调用堆栈在await ReadAsync(serialPort)的末尾溢出了行ReadAsync。我的猜测是等待ReadAsync仍在运行,即使我关闭了SeriaPort,keepReading标志并检查serialPort.IsOpen
因此,如何取消等待ReadAsync的问题是否可能?在这里感谢一些帮助,因为我是初学者。

public async Task ReadAsync(SerialPort serialPort)
    {

            if (serialPort.IsOpen && keepReading)
            {
                try
                {
                        byte[] buffer = new byte[1];
                        await serialPort.BaseStream.ReadAsync(buffer, 0, 1);
                        content += serialPort.Encoding.GetString(buffer);
                        //do sth with content
                        buffer = null;

                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.Message);
                }
                if (keepReading && serialPort.IsOpen)
                    await ReadAsync(serialPort);
            }
    }
private async void Button_Click(object sender, EventArgs e)
    {

        if (serialPort.IsOpen)
        {
            keepReading = false;
            serialPort.Dispose();
            serialPort.Close();
        }
        else
        {
            Open();
            keepReading = true;
            if (serialPort.IsOpen)
            {
                serialPort.DiscardOutBuffer();
                serialPort.DiscardInBuffer();
                await ReadAsync(serialPort);
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

尝试将serialPort.BaseStream.ReadAsync(buffer, 0, 1);包装到另一个异步方法中,并在关闭串行端口之前使用“任务取消”取消此方法。 Cancel an Async Task or a List of Tasks (C#)