I need to protect a buffer (AnsiString object) from being corrupted by simultaneous access to its structure. It is accessed in two ways:
1. on reading from socket -> append to buffer
2. private method called periodically ->search for separator, extract the first part from the buffer by given separator, removing it from the buffer.
I'm noticing the buffer gets corrupted occasionally and I have an idea why. Seems the socket will write into the buffer while is being sliced or vice versa...
The entire logic described above happens inside a single thread (TMyThread). This class contains the socket to read from, the buffer, the critical section and also emulates a timer object by doing the following:
if(MilliSecondsBetween(Now(), lastTimerFired) > 2000)
lastTimerFired = Now();
The TimerLogic() is the method consuming the buffer in the manner I have already described. Although each access to my buffer is protected by Acquire() / Release() don't think it's enough though, as my program crashes rather frequently. The socket OnRead event gets executed in the same thread so I guess TCriticalSection will not help me in this case. I have read that it helps when multiple threading, but not when the happens in the same thread.
What options do I have to solve this problem?
I guess there is the boolean flag option to protect against simultaneous access to the buffer, but I'm not sure this is safe enough...