1
我正在开发一个主要涉及Xbee和PC之间的COM端口通信的winform程序。请允许我首先说明问题:为什么只有在抛出异常后才更新表单
注:
不用担心委托函数,它只是检查返回字节
该项目工程之前,我只是今天增加了高速设置。所以 为xbee设备,我必须先从9600速度,然后改为 无论我需要什么,这是38400.但是,一旦我将它设置为38400, 没有权力循环xbee。当我下次连接设备 时,速度依然为@ 38400。这就是我添加 if(initial_fail)块试图与另一个baud_rate连接的原因。
请跟随我打上编号
try { portBuffer.Clear(); myComPort.Write(myxbee.myxbee_cmd.cmd_mode, 0, myxbee.myxbee_cmd.cmd_mode.Length); //RETURN OK <CR> IAsyncResult res = d.BeginInvoke(null, null); if (res.IsCompleted == false) { res.AsyncWaitHandle.WaitOne(2000, false); if (res.IsCompleted == false) initial_fail = 1; //1. start from here, once there is a timeout, set the initial_fail to 1, Time-out because the baudrate is not sync if (d.EndInvoke(res) == false) throw new Exception("Failing to enter the cmd mode"); } } catch (ApplicationException e) { MessageBox.Show(e.Message); return false; } catch (Exception e) { MessageBox.Show("Error at step 1: {0}", e.Message); return false; } //2. here is the new code I added today if (initial_fail == 1) { myComPort.BaudRate = 38400; //3. Here I changed the speed and gui text cmbBaudRate.Text = "38400"; //PROBLEM: when Im doing step by step debug, seems like these two lines doesnt get executed. Winform GUI remain unchanged try { portBuffer.Clear(); myxbee.command_buffer.Clear(); dummy = "05"; dummy_byte = Encoding.ASCII.GetBytes(dummy); myxbee.command_buffer.AddRange(myxbee.myxbee_cmd.data_rate); myxbee.command_buffer.AddRange(dummy_byte); myxbee.command_buffer.Add(myxbee.myxbee_cmd.line_feed); myComPort.Write(myxbee.command_buffer.ToArray(), 0, myxbee.command_buffer.ToArray().Length); IAsyncResult res1 = d.BeginInvoke(null, null); if (res1.IsCompleted == false) { res1.AsyncWaitHandle.WaitOne(1000, false); if (res1.IsCompleted == false) throw new ApplicationException("Timeout"); //4. since the winform hasnt shown any bd_rate change, the program will throw a time-out here again } if (d.EndInvoke(res1) == false) throw new Exception("Fail in setting data rate to 38400"); chkHighSpeed.Checked = true; high_speed_set = 1; MessageBox.Show("Xbee high speed"); } catch (ApplicationException e) { MessageBox.Show(e.Message); return false; //5. BUT AFTER THIS TIMEOUT message, the winform's GUI will be updated to 38400, and rerun the whole test will pass }
这是GUI的部分看起来像评论:
所以我的问题是,为什么超时异常后只,那么波特率会被更新?
此处为背景工作者示例的网址http://www.dotneat.net/2009/02/10/BackgroundworkerExample.aspx – 2012-08-12 03:05:01