2011年3月16日 星期三

Visual 2008 C# SerialPort RX thread issue.

平台 Windows XP 32bit, Profilc PL2303
Language Visual 2008 C#

遇到的問題是Serial Port的接收使用Threading的方式作.

程式片段
static Thread comport_recv_thread;
static bool comport_recv_thread_flag;
void comport_open()
{
comport_recv_thread = new Thread(comport_recv);
....set com port...
comport_recv_thread_flag = true;
serialPort1.ReadTimeOut = 500;
serialPort1.Open();
comport_recv_thread.Start();
}

void comport_close()
{
comport_recv_thread_flag = false;

//while(serialPort1.IsAlive);
// Die

//while(true) if(serialPort1.IsAlive == false)
//comport_recv_thread.Join();
//Die

//comport_recv_thread.Join();
// Die

//timer1.Interval = 2000;
//timer1.Tick += new EventHandler(comport_close_by_timer);
//timer1.Start()
// Work but when open again, will error.

while(serialPort1.IsAlive) Application.DoEvents();
// Work.
serialPort1.Close();
}

private void comport_recv()
{
while(comport_thread_flag)
{
//Do something
try
{
//Read from serial port
}
catch(TimeoutException)
{ }
}
}

感覺問題是出在Read Time out 的時間點
只要還沒出現timeout的情形下使用Join()
程式就會卡死沒有反應

同時若是有一個空迴圈在跑也會影響到timeout.
目前是用Application.DoEvents();
不讓迴圈搶走太多資源 同時也讓timeout可以動作