gpt4 book ai didi

c# - 尝试结束线程时发生 System.IO.IOException 异常

转载 作者:太空狗 更新时间:2023-10-29 21:46:29 26 4
gpt4 key购买 nike

我正在 Monodevelop 中学习网络代码和多线程,使用 C# 和 GTK#。我以前从未做过,现在我发现自己需要同时做这两件事。

我使用了一个没有错误处理的教程聊天程序,每次我与服务器断开连接时,我都会发现客户端发生错误。位于监听消息的线程中的代码如下,由 try/catch 语句包围:

            try
{
while (Connected)
{
if (!srReceiver.EndOfStream && Connected)
{
string temp = srReceiver.ReadLine();
// Show the messages in the log TextBox
Gtk.Application.Invoke(delegate
{
UpdateLog(temp);
});
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

之后函数完成,线程结束。

结束连接的代码如下所示,并在主线程上运行:

        private void CloseConnection(string Reason)
{
// Show the reason why the connection is ending
UpdateLog(Reason);
// Enable and disable the appropriate controls on the form
txtIp.Sensitive = true;
txtUser.Sensitive = true;
txtMessage.Sensitive = false;
btnSend.Sensitive = false;
btnConnect.Label = "Connect";

// Close the objects
Connected = false;
swSender.Close();
srReceiver.Close();
tcpServer.Close();
}

上面的 try/catch 语句捕获了这个错误:

System.IO.IOException: Unable to read data from the transport connection: A blocking operation was interrupted by a call to WSACancelBlockingCall. ---> System.Net.Sockets.SocketException: A blocking operation was interrupted by a call to WSACancelBlockingCall

at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)

at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)

--- End of inner exception stack trace ---

at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)

at System.IO.StreamReader.ReadBuffer()

at System.IO.StreamReader.get_EndOfStream()

at ChatClientGTK.MainWindow.ReceiveMessages() in g:\Android\Tutes\ChatClientRemake\ChatClientGTK\MainWindow.cs:line 157

现在,据我所知,当 srReciever.Close() 在主线程中发生时,srReciever.ReadLine() 仍在尝试在监听线程中执行,这就是问题所在,但即使我注释掉srReciever.Close(),还是报错。

据我所知,仅捕获错误并继续操作不会产生任何副作用,但我并不认同这一点。我是否需要修复此错误?如果需要,有人有任何想法吗?

最佳答案

除了使用 ReadLine,您不能只执行读取并构建字符串直到检测到 CrLf,然后将其输出到更新日志。

ReadLine 是一个阻塞调用,这意味着它会坐在那里,如果连接关闭,它总是会出错。

否则你可以忽略这个错误。当您说它不正确时,我知道您的意思,但是除非其他人可以启发我,否则我看不到资源因此而泄漏,如果这是预期的错误,那么您可以适本地处理它.

另外我可能会捕获特定的异常

catch (IOException ex)
{
Console.WriteLine(ex.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

关于c# - 尝试结束线程时发生 System.IO.IOException 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8752939/

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