Closing NetworkStream after calling BeginRead () in C #

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);

        //append received data to the string buffer
        stringBuffer += System.Text.ASCIIEncoding.ASCII.GetString(buffer);

        //clear the byte array
        Array.Clear(buffer, 0, buffer.Length);

        //trigger the parser
        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?

+5
1

GetStream - .

Stream nstrm = server.GetStream();

nstrm NetworkStream...

- disconnect().

DataReceived EndRead , , :

server.Close();
nstrm.Close();

. http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.getstream.aspx

EDIT - :

if (flag2Close)
{
    server.Close();
    nstrm.Close();
    flag2Close = false;
}
else
{
    nstrm.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(DataReceived), buffer);
}

BTW: ..

+1

All Articles