解决我的对象处置异常
您好,any1 可以告诉我在哪里尝试捕获此异常或解决它。当我关闭接收句柄时,如果我仍然收到一些数据,则会出现此错误。
public partial class Form1 : Form
{
SerialPort sp;
IAsyncResult recv_result;
string buffer;
private delegate string ReadLine_Delegate();
private void button1_Click(object sender, EventArgs e)
{
try
{
sp = new SerialPort("COM8", 9600);
sp.Open();
sp.ReadTimeout = 50000;
sp.NewLine = "\n\r\0";
ReadLine_Delegate x = new ReadLine_Delegate(sp.ReadLine);
recv_result = x.BeginInvoke(new AsyncCallback(ReadLine_Callback),
x);
}
catch (Exception ex)
{
}
}
private void ReadLine_Callback(IAsyncResult iar)
{
ReadLine_Delegate y = (ReadLine_Delegate)iar.AsyncState;
try
{
buffer = y.EndInvoke(iar);
}
catch
{
MessageBox.Show("Error");
return;
}
ListBoxAdd(buffer);
buffer = "";
recv_result = y.BeginInvoke(new AsyncCallback(ReadLine_Callback), y);
}
private void disconnectButton_Click(object sender, EventArgs e)
{
recv_result.AsyncWaitHandle.Close();
sp.Close();
}
}
Hello can any1 tell me where to try catch this exception or solve it. Whenver i close my receive handle, if i still recieved some data, it comes up with this error.
public partial class Form1 : Form
{
SerialPort sp;
IAsyncResult recv_result;
string buffer;
private delegate string ReadLine_Delegate();
private void button1_Click(object sender, EventArgs e)
{
try
{
sp = new SerialPort("COM8", 9600);
sp.Open();
sp.ReadTimeout = 50000;
sp.NewLine = "\n\r\0";
ReadLine_Delegate x = new ReadLine_Delegate(sp.ReadLine);
recv_result = x.BeginInvoke(new AsyncCallback(ReadLine_Callback),
x);
}
catch (Exception ex)
{
}
}
private void ReadLine_Callback(IAsyncResult iar)
{
ReadLine_Delegate y = (ReadLine_Delegate)iar.AsyncState;
try
{
buffer = y.EndInvoke(iar);
}
catch
{
MessageBox.Show("Error");
return;
}
ListBoxAdd(buffer);
buffer = "";
recv_result = y.BeginInvoke(new AsyncCallback(ReadLine_Callback), y);
}
private void disconnectButton_Click(object sender, EventArgs e)
{
recv_result.AsyncWaitHandle.Close();
sp.Close();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我很确定发生的情况是您正在另一个线程上执行阻塞的
ReadLine()
调用(通过委托的BeginInvoke
),但随后调用Close()
在SerialPort
上,而它仍在ReadLine()
调用中。当数据进入现已关闭(并因此被处置)的端口时,将引发异常。通常的解决方案是在所有未完成的读取完成之前不要关闭端口。您可能需要设置读取超时,以确保它在某个时刻返回。请参阅此处的示例更多信息。
I'm pretty sure what's happening is that you are executing the blocking
ReadLine()
call on another thread (via your delegate'sBeginInvoke
) but then callingClose()
on theSerialPort
while it is still in theReadLine()
call. When data comes in on the now closed (and thus disposed) port, the exception is thrown.The usual solution is to not close the port until any outstanding reads have finished. You may need to set a timeout on the read in order to ensure it will return at some point. See the example here for more info.
锁定块可能会解决 ReadLine_Callback 内的问题。另请检查 IAsyncResult.IsCompleted 状态。
lock block would probably solve your problem inside the ReadLine_Callback. Also check the IAsyncResult.IsCompleted status.