gpt4 book ai didi

c# - 停止 Stream.BeginRead()

转载 作者:太空狗 更新时间:2023-10-30 01:25:31 30 4
gpt4 key购买 nike

我需要从我的虚拟 com 端口读取数据并检测消息“Dreq”。一旦我按下连接按钮,它就会连接到我的 COM8 端口并开始读取新线程。我还有一个断开连接按钮,我希望在其中关闭读数并断开与 COM8 端口的连接。但是,我在关闭 BeginRead 时遇到问题。

public partial class Form1 : Form
{
SerialPort sp;
Stream stream;
IAsyncResult recv_result;

private void button1_Click(object sender, EventArgs e)
{
sp = new SerialPort("COM8", 9600);
sp.Open();
sp.ReadTimeout = 50000;
sp.NewLine = "\n\r\0";
stream = sp.BaseStream;
recv_result = stream.BeginRead(new byte[1], 0, 0, new
AsyncCallback(ReadCallBack), stream);
}

private void ReadCallBack(IAsyncResult ar)
{
Stream stream = (Stream)ar.AsyncState;
string temp;

while (stream.CanRead)
{
temp = sp.ReadLine();
// ... do something with temp
}
}

private void disconnectButton_Click(object sender, EventArgs e)
{
stream.EndRead(recv_result);
sp.Close();
}
}

最佳答案

您可以尝试调用 sp.DiscardOutBuffer()。它将调用您的读取回调,然后您可以使用 stream.EndRead()

private void disconnectButton_Click(object sender, EventArgs e)
{
sp.DiscardOutBuffer();
stream.EndRead(recv_result);
sp.Close();
}

关于c# - 停止 Stream.BeginRead(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6759938/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com