我正在使用C#和GTK#在Monodevelop中学习网络代码和多线程.我以前从未做过,现在我发现自己需要同时做两件事.
我使用了一个没有错误处理的教程聊天程序,我发现每次与服务器断开连接时都会在客户端发生错误.位于侦听消息的线程中的代码如下所示,由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());
}
Run Code Online (Sandbox Code Playgroud)
之后函数完成并且线程结束.
结束连接的代码如下所示,并在主线程上运行:
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";
// …Run Code Online (Sandbox Code Playgroud)