Serial communication-PortClose()

Hi,

I am working on a serial communication program in VC MFC, the data communication goes well.

My problem is: when I click on Cancle to close the app, it hangs, just no response. I found it resulted from" if (!CloseHandle (hCommPort))".

Does anyone know how to fix it? Any code or link will be thankful.

My code is the same as in MSDN serial communication->sample.

BOOL PortClose (HANDLE hCommPort)
{
DWORD dwError;

if (hCommPort != INVALID_HANDLE_VALUE)
{
// Close the communication port.
if (!CloseHandle (hCommPort)) <-
{
dwError = GetLastError ();
return FALSE;
}
else
{
hCommPort = INVALID_HANDLE_VALUE;
return TRUE;
}
}

connie
[849 byte] By [connie_liyang] at [2007-11-18 18:21:37]
# 1 Re: Serial communication-PortClose()
Hi,

Use PurgeComm(m_hCommPort, PURGE_TXABORT|PURGE_RXABORT) and then call CloseHandle()
rajmathi_mehta at 2007-11-11 1:21:30 >
# 2 Re: Serial communication-PortClose()
Thanks for you reply.

But the code now hangs at PurgeComm().

connie
connie_liyang at 2007-11-11 1:22:30 >
# 3 Re: Serial communication-PortClose()
Hello Connie,

could you please tell what is happening at the backgroung when cancel is clicked ... do u have any threads which share the comm handle?
rajmathi_mehta at 2007-11-11 1:23:31 >
# 4 Re: Serial communication-PortClose()
Hi,

has anyone solved this problem so far? It seems that a have a similar topic and cannot find a reason for this behaviour.

Regards,

Max
M. E. at 2007-11-11 1:24:26 >
# 5 Re: Serial communication-PortClose()
You have to make sure you clean up your Serial Class resources..

Such as any Overlap objects for your Read/Write functions. Anything that is put on the heap (new) must be deleted (delete) from heap.

If your using Critical Sections in your class

//ex.
DeleteCriticalSection(&m_csSMCommunicationSync);
/////

You should have a Termination Function to not only close the port but cleanup your resources in your Serial port class.
Jim Mcpherson at 2007-11-11 1:25:25 >
# 6 Re: Serial communication-PortClose()
Also, If you have a separate thread that is reading the serial port, you need to terminate this thread in your Termination function.
Jim Mcpherson at 2007-11-11 1:26:32 >