hipswich

I have an application coded in C# using NETCF. It opens and uses a Bluetooth virual serial port without any problem. It can get data continuously for days flawlessly. However, frequently the application hangs when exiting. I have to use Task Manager to close the program. By debugging, I found it is the code closing the serial port during the exit process causes the haning. The code is as simple as sp.Close(); where sp is the serial port.

Any tip to help with this will be greatly appreciated.




Re: Smart Devices VB and C# Projects Problem in Closing Bluetooth Virtual Serial Port

Selva kumar

Can you please post the Code snippet...

So that we can try.





Re: Smart Devices VB and C# Projects Problem in Closing Bluetooth Virtual Serial Port

hipswich

Thanks, Selva, for willing to help.

I should have posted my proegressearlier. I have solved the problem. Per your request, the code for the exit function is appended to this post (the indentation was lost by pasting). I did a few things to make sure other threads do not use the serial port in any way once flags such as bApplicationRunning become false. but the key change I made is probably adding the following

if (sp.IsOpen)

{

sp.DataReceived -= SerialPort_DataReceived; //remove the event handlers

}

Apparently just calling sp.Close() is not good enough.

Now, the application always exits gracefully under many condtions that I have tested.

Cursor.Current = Cursors.WaitCursor;

timer1.Enabled = false;

bApplicationRunning = false;

bTCPConnection = false;

if (sp.IsOpen)

{

sp.DataReceived -= SerialPort_DataReceived; //remove the event handlers

}

Thread.Sleep(1500); //wait for other threads to exit

try

{

if (sp.IsOpen)

{

sp.Close();

}

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

}

try

{

if ((tcpClient != null) && (tcpClient.Client.Connected))

{

ns.Close();

tcpClient.Close();

bTCPConnection = false;

}

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

}

Cursor.Current = Cursors.Default;

this.Close();