I implemented a system that simulates a serial port DataReceived event, as a result of which the reading of data from a TCPClient NetworkStream object is started using the BeginRead () method as follows:
TcpClient server = new TcpClient();
server.Connect(IPAddress.Parse(ip), 10001);
server.GetStream().BeginRead(buffer, 0, buffer.Length, new AsyncCallback(DataReceived), server.GetStream());
which calls the following method from another thread:
private void DataReceived(IAsyncResult result)
{
res = result;
server.GetStream().EndRead(result);
stringBuffer += System.Text.ASCIIEncoding.ASCII.GetString(buffer);
Array.Clear(buffer, 0, buffer.Length);
waitHandle.Set();
server.GetStream().BeginRead(buffer, 0, buffer.Length, new AsyncCallback(DataReceived), buffer);
}
This is working correctly. I can send and receive data to a device on the network without problems. However, when I try to disconnect using the following method, the program crashes:
public override void disconnect()
{
server.Close();
}
It produces the following error:
A first chance exception of type 'System.ObjectDisposedException' occurred in System.dll
I also tried to implement the disconnect method as follows:
server.GetStream().Close();
but this leads to the following error:
A first chance exception of type 'System.InvalidOperationException' occurred in System.dll
I assume this has to do with the fact that the BeginRead () method was called, and the EndRead () method did not. If so, how can I close a stream without crashing it?