Sto imparando netcode e multithreading in Monodevelop, utilizzando C# con GTK #. Non l'ho mai fatto prima, e ora mi trovo a doverli fare entrambi contemporaneamente.Eccezione System.IO.IOException durante il tentativo di terminare il thread
Ho utilizzato un programma di chat tutorial che non ha errori di gestione e ho rilevato un errore che si verifica nel client ogni volta che si disconnette dal server. Il codice che si trova in un thread di ascolto per i messaggi è il seguente, circondato da dichiarazioni 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());
}
Dopo che le finiture di funzione e le estremità del filo.
Il codice che termina il collegamento si presenta così, e viene eseguito sul thread principale:
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();
}
E il try/catch dichiarazioni di cui sopra cattura questo errore:
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
Ora, per quanto come posso dire, quando srReciever.Close() accade nel thread principale, srReciever.ReadLine() sta ancora provando ad eseguire nel thread di ascolto, che è dove si trova il problema, ma anche quando commento a srReciever.Close() , Ho ancora l'errore.
Per quello che posso dire, non ci sono effetti collaterali causati dal semplice rilevamento dell'errore e dall'andare avanti, ma questo non mi sta proprio bene. Devo correggere questo errore e, in caso affermativo, qualcuno ha qualche idea?
Solo un altro esempio di un'eccezione generata per indicare una condizione non eccezionale. La maggior parte delle persone considera che una cattiva progettazione dell'API, ma con .NET BCL è normale. –