title: EndRead throws IO exception
body: <p>This is for local communication between a MoSync application and an external DLL, MoSync does not allow me to use 3rd part DLLs and that is the reason why I have to implement this bridge software instead of using a simple call to a DLL, I have to convert from xml to the DLL Message format, and again to XML. I know this is a dumb thing, unfortunately there is no flexibility to change the architecture. Initially i thought that there was only one request so I had Sync coms but now I find out there can be more than one request, so I need to implement Async back again.</p>
  
  <p>I have an exception that is thrown from time to time, since I am new to C# I am unable to find the memory leak... perhaps a pair of more well trained eyes can find the issue</p>
  
  <p>SOURCE CODE:</p>
  
  <p>I have written the following code, I am quite new to C# and Sockets, so perhaps I have made some big mistakes that only more experienced eyes can detect. This is to be used in a Windows Mobile 6.1 device, so I am trying to avoid using many threads.</p>
  
  <pre><code>using System;
  
  using System.Collections.Generic;
  using System.Text;
  using System.Net.Sockets;
  using System.Net;
  using System.Threading;
  using System.Diagnostics;
  
  namespace SmartDevice_Server
  {
      //ClientConnection saves connection information is used to keep context in Async and Event calls
      public class ClientConnection : EventArgs
      {
          public NetworkStream NetworkStream { get; private set; }
          public byte[] Data { get; private set; }
          public int byteReadCount { get; set; }
  
          public ClientConnection(NetworkStream networkStream, byte[] data)
          {
              NetworkStream = networkStream;
              Data = data;
          }
      }
  
      //MySocket - Is a server that listens for events and triggers Events upon Request Completion 
      public class MySocketTCP
      {
          #region Class Members
          TcpListener myTcpListener;
          TcpClient myTcpClient;
          NetworkStream myNetworkStream;
  
          const string localHost = "127.0.0.1";
          IPAddress myAddress = IPAddress.Parse(localHost);
          int myPortNumber = 58889;
          byte[] myData;
  
          int bytesReadCount;
          const int MIN_REQUEST_STRING_SIZE = 10;
  
          int TimeStart;
  
          //Event
          public event socketReadCompleteHandler socketReadCompleteEvent;
          public EventArgs eventArguments = null;
          public delegate void socketReadCompleteHandler(MySocketTCP myTcpSocket, ClientConnection eventArguments);
  
          #endregion
  
          //Constructor
          public MySocketTCP()
          {
              Init();
          }
  
          //Constructor overloaded to receive IPAdress Host, and Port number
          public MySocketTCP(IPAddress hostAddress, int portNumber)
          {
              myAddress = hostAddress;
              myPortNumber = portNumber;
  
              Init();
          }
  
          //Initializes the TCPListner
          public void Init()
          {
              try
              {
                  myTcpListener = new TcpListener(myAddress, myPortNumber);
  
                  //myNetworkStream = myTcpClient.GetStream();
              }
              catch (Exception ex)
              {
                  throw ex;
              }
          }
  
          /*TODO_Listener_Timer: After you accept a connection you wait for data to be Read indefinitely
           *Possible solution: Use a timeout to close the socket connection.
           *Check WIKI, TODOS
           * */
          //Listens Asynchronously to Clients, class a recieveMessageHandler to process the read
          public void ListenAsync()
          {
              myTcpListener.Start();
  
              while (true)
              {
                  //blocks until a client has connected to the server
                  myTcpClient = myTcpListener.AcceptTcpClient();
  
                  var client = new ClientConnection(myTcpClient.GetStream(), new byte[myTcpClient.ReceiveBufferSize]);
  
                  // Capture the specific client and pass it to the receive handler
                  client.NetworkStream.BeginRead(client.Data, 0, client.Data.Length, r =&gt; receiveMessageHandler(r, client), null);
              }
          }
  
          //Callback is used to Process the request Asynchronously, triggers socketReadCompleteEvent
          public void receiveMessageHandler(IAsyncResult asyncResult, ClientConnection clientInstance)
          {
              bytesReadCount = 0;
  
              lock (clientInstance.NetworkStream)
              {
                  try
                  {
                      bytesReadCount = clientInstance.NetworkStream.EndRead(asyncResult);
                      clientInstance.byteReadCount = bytesReadCount;
                  }
                  catch (Exception exc)
                  {
                      throw exc;
                  }
              }
  
              if (bytesReadCount &lt; MIN_REQUEST_STRING_SIZE)
              {
                  //Could not read form client.
                  Debug.WriteLine("NO DATA READ");
              }
              else
              {
                  if (socketReadCompleteEvent != null)
                  {
                      socketReadCompleteEvent(this, clientInstance);
                  }
              }
          }
  
          //Reads the request, uses the ClientConnection for context
          public string ReadAsync(ClientConnection connObj)
          {
              int bytesReadCount = connObj.byteReadCount;
              byte[] myData = connObj.Data;
  
              string xmlMessage;
  
              try
              {
                  xmlMessage = Encoding.ASCII.GetString(myData, 0, bytesReadCount);
              }
              catch (Exception ex)
              {
                  throw ex;
              }
  
              return xmlMessage;
          }
  
          //Deprecated
          public string Read()
          {
              string xmlMessage;
  
              try
              {
                  xmlMessage = Encoding.ASCII.GetString(myData, 0, bytesReadCount);
              }
              catch (Exception ex)
              {
                  throw ex;
              }
  
              return xmlMessage;
          }
  
          //Deprecated
          public void Write(byte[] outBytes)
          {
              try
              {
                  myNetworkStream.Write(outBytes, 0, outBytes.Length);
              }
              catch (Exception ex)
              {
                  throw ex;
              }
          }
  
          //Deprecated
          public void Write(string outMessage)
          {
              byte[] outBytes = Encoding.ASCII.GetBytes(outMessage);
  
              try
              {
                  myNetworkStream.Write(outBytes, 0, outBytes.Length);
              }
              catch (Exception ex)
              {
                  throw ex;
              }
  
              int TimeEnd = Environment.TickCount;
              int TimeResult = TimeEnd - TimeStart;
          }
  
          //Is used to send the message to the correct socket
          public void WriteAsync(ClientConnection connObj, string outMessage)
          {
              byte[] outBytes = Encoding.ASCII.GetBytes(outMessage);
  
              try
              {
                  connObj.NetworkStream.Write(outBytes, 0, outBytes.Length);
              }
              catch (Exception ex)
              {
                  throw ex;
              }
  
              int TimeEnd = Environment.TickCount;
              int TimeResult = TimeEnd - TimeStart;
          }
  
          //Closes the client
          public void Close()
          {
              //myNetworkStream.Close();
              try
              {
                  myTcpClient.Close();
              }
              catch (Exception ex)
              {
  
                  throw ex;
              }
          }
      }
  }
  </code></pre>