Thread and stop button

Hello all,

I have wrote a program with serial communication. I have a thread class which reads from com port. There is a StopButton, which I can click if there is any data on the com port. The problem is when there isn't data on the comport, the thread are working, but GUI of the program hangs up. How can I make, that I can click StopButton?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//---------------------------------------------------------------------------
void __fastcall some_tread::Request()
{
 DWORD dwRead;
 buf_pos = 0;
 bool t = false;

 while (!t && !Terminated)
  {
   if (!ReadFile(hCom, &C, 1, &dwRead, &ReadOverlapInformation1))
   {
    DWORD ErrorCode = GetLastError();
    if (ErrorCode == ERROR_IO_PENDING) {
     WaitForSingleObjectEx(ReadEvent,INFINITE,TRUE);
     GetOverlappedResult(hCom,&ReadOverlapInformation1,&dwRead,false);
     if (!Terminated && dwRead) buffer[buf_pos++] = C;
    }
   }
   else {
    if (!Terminated && dwRead) buffer[buf_pos++] = C;
   }
  t = CheckFor();
 }
}
//---------------------------------------------------------------------------
void __fastcall some_tread::Execute()
{
 ReadEvent = CreateEvent(NULL,false,false,NULL);
 ReadOverlapInformation1.hEvent = ReadEvent;
 FreeOnTerminate = true;
 while (!Terminated) {
  Synchronize((TThreadMethod)&Request);
  Sleep(33);
 }
}
Last edited on
1
2
3
4
5
6
7
   if (!ReadFile(hCom, &C, 1, &dwRead, &ReadOverlapInformation1))
   {
    DWORD ErrorCode = GetLastError();
    if (ErrorCode == ERROR_IO_PENDING) {
     WaitForSingleObjectEx(ReadEvent,INFINITE,TRUE);
     GetOverlappedResult(hCom,&ReadOverlapInformation1,&dwRead,false);
    }

is equivalent to:
1
2
   if (!ReadFile(hCom, &C, 1, &dwRead, NULL))
   {

You need to wait for some timeout, then check if Terminated is flagged. At the moment, it's not working because you're waiting indefinitely.

A better way to do this would be to make Terminated an Event rather than a bool. Then you could do WaitForMultipleObjects on both ReadEvent and Terminated with an infinite timeout.
Topic archived. No new replies allowed.