简体   繁体   English

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

[英]How to cancel await SerialPort.BaseStream.ReadAsync?

My c# WinForms application reading asynchronously from serial port. 我的c#WinForms应用程序从串行端口异步读取。 It works, but when the port closes, an StackOverflowException appears. 它可以工作,但是当端口关闭时,将显示StackOverflowException The Call Stack is overflowed with line await ReadAsync(serialPort) on the end of ReadAsync . await ReadAsync(serialPort)的末尾,调用堆栈由行await ReadAsync(serialPort) ReadAsync My guess is the line await ReadAsync still run even though I close SeriaPort, keepReading flag and checking serialPort.IsOpen . 我的猜测是,即使我关闭了SeriaPort, keepReading标志并检查serialPort.IsOpen ,等待ReadAsync的行仍在运行。
Hence the question, how to cancel await ReadAsync, is it possible? 因此,如何取消等待ReadAsync的问题是可能的吗? Appreciate some help here because I'm beginner. 在这里感谢一些帮助,因为我是新手。

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);
            }
        }
    }

Try to wrap serialPort.BaseStream.ReadAsync(buffer, 0, 1); 尝试包装serialPort.BaseStream.ReadAsync(buffer, 0, 1); into another async method and use Task Cancellation to cancel this method before you close the serial port. 转换为另一种异步方法,并在关闭串行端口之前使用“任务取消”取消此方法。 Cancel an Async Task or a List of Tasks (C#) 取消异步任务或任务列表(C#)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM