I have an app that downloads data of very different sizes from a server.
I use a single thread to process the downloads. One type of data is very large and has very important header info in the first few bytes.
I create a EnterCriticalSection() as the socket buffer is translated and call LeaveCriticalSection() when all the current data has been dealt with.
(the CRITICAL_SECTION variable has been init only once as the app starts)
This works perfectly until I add the MessageBox().
In debugging I added a MessageBox to inform me the first part of the data had been successfully translated (and uncompressed). Some of the data is still to be translated, it is only the first part of the data that has been delt with (I get a partial read as it is from multiple writes to the socket and the data size is large).
The function should return to the data translation function and use the rest of the buffer to fill in the partial data before again trying to read more data from the socket.
At this point the app seems to create another thread for the MessageBox allowing the rest of the app to continue, without using the partial data in the translate function. (that is the thread that calls MessageBox() does not continue but does not stop ). LeaveCriticalSection() does not get called this time.
The rest of the data is read from the socket (by the original thread) and sent to the function to translate it. Unfortunately some data is still in the function waiting for the user to press the OK button on the MessageBox.
The function should not be able to enter the critical section but the thread that calls is the same as the one ALREADY in the function! That is the original thread (that 'Entered' the critical section) has not exited but is again at the start of the function asking to enter the critical section again.
EnterCriticalSection() thinks that it is a recursive function and allows the thread to continue, causing a 'very BAD THING' to happen.
As I said if the MessageBox is not there the function works as expected / desired (as it does with my own version of a messagebox ie a dialog with a static text displayed on it).
Is there something I am doing wrong?
Any explanations / ideas why the MessageBox can do this?
Code://data read from socket EnterCriticalSection(&CS); while (iUsed<iRead) { //read header, alloc memory and process //read data and fill memory if(iNeeded>=iRead-iUsed) //not enough data in current buffer { //save memory offset //partiallly fill buffer } else//have all the data { //fill buffer //process data MessageBox(hWnd, "Data processed.", szApp, MB_OK); } iUsed+=Data_Copied; } LeaveCriticalSection(&CS); return;