Asynch Socket read seems to ignore my lock()
-
I have a little asynch. socket listener that notifies me when data is read. inside of the OnRead callback event it seems that my notifications were overlaping (future notifications triggered before past notifications 1.2.3.4.5. becomes 1.2.5.3.4.). The code goes like this:
private void OnReadComplete( IAsyncResult ar )
{
... copy the m_byBuffer data into byOut ...
... do some work ...lock(m_ReadLockObject) <-- should block the next read attempt.
{
// Continue reading
if (m_netStream.CanRead && (m_Socket.Connected || m_netStream.DataAvailable))
m_netStream.BeginRead(m_byBuffer, 0, m_byBuffer.Length, m_callbackRead, null);// Trigger Read Data event. if (bytesRead > 0) ExecOnDataRead(this, new CClientInfoEventArgs(m\_EndPoint, byOut));
}
...
}The data keeps comming in all jumbled up. Now I can patch this by putting in a sufficiently large delay, like a trace before and after I call ExecOnDataRead to check the current thread ID, OR I can re-arrange the ExecOnDataRead before the BeginRead. The thing is that I know ExecOnDataRead can be quite expensive and I do perform some work before I pass the data on, so I want the next BeginRead to be running while I'm doing that. Note that a simple trace or debug seems to straighten out the data (obviously time sensitive) so I can't observe what is happening except through the end results. Even putting in a second lock inside ExecOnDataRead, or a static mutex.WaitOne() does not seem to straighten out the data, but as soon as I put in a Trace to print out the thread ID's that are running the ExecOnDataRead to see if they are overlapping, everything straightens out!! Ahrrgg! It's almost like the lock is not locking.:sigh: Thanks in advance
Assert(this);