I don't think sleep is needed.
Second problem is, because I have to use Sleep() in the file read loop, reading a 1 GB file takes more than 20 minutes.
You need to set m_bAutoDelete to false and make sure the thread isn't running. I do
Third problem is, whenever I put delete MyThread, my application always crashes. Any idea?
The reason I first create the thread suspended is that the thread could conceivably complete before m_bAutoDelete is asigned. This way the thread is suspended when the m_bAutoDelete is assigned. The Website link I gave to you before goes into more depth. When I make sure to wait for the thread to exit. I do
CWinThread* thread = AfxBeginThread(run, 0, THREAD_PRIORITY_NORMAL,
thread->m_bAutoDelete = false;
I know when this code is run the thread is about to exit because this code is executed when the view receives UWM_FINISHED_READ(which is posted to the view when the thread is about to exit). Before this code is executed, the static stop variable is set inside the thread so that the thread proc will eventually exit.
readWorkerThread_ = 0;
The thread callback itself might look something like
The stop_ variable is declared volatile because it is changed and read from two different threads. The windows that receive the messages are responsible for deleting their parameters.
UINT ReadWorker::run(LPVOID paramPtr)
int lineno = 0;
while(!stop_ && !in.eof())
ProgressInfo* info = new ProgressInfo(lineno, line);
WPARAM wp = reinterpret_cast<WPARAM>(info);
PostMessage(view_, UWM_PROGRESS_UPDATE, wp, 0);
bool isCancelation = stop_;
ReadFinishInfo* finfo = new ReadFinishInfo(isCancelation);
WPARAM wpInfo = reinterpret_cast<WPARAM>(finfo);
PostMessage(view_, UWM_FINISHED_READ, wpInfo, 0);