I have a thread in a function which start the live monitoring, it basically, opens the serial port and continously reading data from serial port. However, If I need to terminate this thread, how should I do it? Because If I don't terminate the running thread which opened the specific serial port and reading data. When I close it and call the function again. The same serial port cannot opened. I suspect that the serial port is not closed properly and is still running in a seperate thread. So I think i have to terminate that thread in order to open the same serial port again next time. Does anyone have any idea of how to achieve this?
I have seen some forum said that Thread.Abort() is dangerous to use. It should only be used in last resort.
Thanks for any helps.
Charles
Generally, you design the method that is run in the background thread to listen for cancellation requests. This can be as simple as a boolean value:
//this simply provides a synchronized reference wrapper for the Boolean,
//and prevents trying to "un-cancel"
public class ThreadStatus
{
private bool cancelled;
private object syncObj = new Object();
public void Cancel() {lock(syncObj){cancelled = true;}}
public bool IsCancelPending{get{lock(syncObj){return cancelled;}}}
}
public void RunListener(object status)
{
var threadStatus = (ThreadStatus)status;
var listener = new SerialPort("COM1");
listener.Open();
//this will loop until we cancel it, the port closes,
//or DoSomethingWithData indicates we should get out
while(!status.IsCancelPending
&& listener.IsOpen
&& DoSomethingWithData(listener.ReadExisting())
Thread.Yield(); //avoid burning the CPU when there isn't anything for this thread
listener.Dispose();
}
...
Thread backgroundThread = new Thread(RunListener);
ThreadStatus status = new ThreadStatus();
backgroundThread.Start(status);
...
//when you need to get out...
//signal the thread to stop looping
status.Cancel();
//and block this thread until the background thread ends normally.
backgroundThread.Join()
First think you have thread in it and to close all your threads you should set all of them to background threads before you start them then they will be closed automatically when the application exits.
And then try this way:
Thread somethread = new Thread(...);
someThread.IsBackground = true;
someThread.Start(...);
Refer http://msdn.microsoft.com/en-us/library/aa457093.aspx
Use a boolean flag you set to false initially and when you want your thread to quit you set it to true. Apparently your main thread loop needs to monitor that flag. When it sees that it changes to true then quite your polling, close the port and exit the main thread loop.
Your main loop could look like this:
OpenPort();
while (!_Quit)
{
... check if some data arrived
if (!_Quit)
{
... process data
}
}
ClosePort();
Depending on how you wait for new data you might want to make use of events (ManualResetEvent
or AutoResetEvent
) in order to wake up your thread when you want it to quit.