Click here to Skip to main content
15,352,155 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
C#
main()
{

thread_B.start();
thread_A.start();

}


public void Thread_A()
{
    while(true)
        if (State == 1)
        {
            try
            {
                Thread_B.Interrupt();
                if (!thr.Join(5000))
                {
                    Thread_B.Abort();
                    GC.Collect();
                    Thread_B.ExecutionContext.Dispose();
                    //    State = 0;
                    // From here i want to end thread safely    
                    // Application must not restart
                   
                }
                Console.WriteLine("\nInsert_Dongle");
            }
            catch (Exception e)
            { }
        }
}


Thread Thread_B= new Thread(delegate()
{
    State = TLoop();
});

public static int TLoop()
{

while(true)
// some error found
return 1;//


}



i am opening serial port in thread _B
if some one removes the serial cable when code is running incoming data stops but the serial port is still opened if i tried to close the serial port it gives

" unhandled exception system.ObjectDisposedException occured in mscorlib.dll addition information : Safe handle has been closed"


how to close the comport?
Posted
Updated 9-Nov-11 21:45pm
v2
Comments
   
Extremely bad threading, pointless use of GC, but a good question.
--SA

Don't abort the thread.
Instead, use a timeout on the SerialPort (SerialPort.ReadTimeout Property[^] which will cause the read operation to throw a timeout exception). Use a semaphore to tell the thread to terminate when it can, and let it close down in an orderly way.
   
Comments
01.mandar 10-Nov-11 3:55am
   
on ReadTimeout i wait for some time and recheck for any data on port on Bluetooth.
problem occurs when the code is running and Bluetooth serial dongle is removed
event occurs is "the device does not recognize the command"
so i need to close the thread which reads data on serial port and restart thread after some time.
http://connect.microsoft.com/VisualStudio/feedback/details/140018/serialport-crashes-after-disconnect-of-usb-com-port[^]
has partially resolved from above link.
i am still getting IO exception for the ports , but the application is not crashing (at least for now) :)
   
<configuration>
<runtime>
<legacyUnhandledExceptionPolicy enabled="1"/>
</runtime>
</configuration>

I have tried with this and it helped me from spending more time on it...
At least no Application crashing is happening now...
Thanks to Justin Wignall(http://stackoverflow.com/questions/3230311/problem-with-serialport[^]) and Hans Passant (http://stackoverflow.com/questions/3230311/problem-with-serialport[^])
   
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900