2012-12-03 35 views
0

我得到了全局变量SerialPort comm;打开COM端口后读取recived字节,我得到的例外,COM端口关闭..
我如何才能在backgroundworker中正确访问它?
是否有更好的方法来声明comm?BackgroundWorker和访问全局变量

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
{ 
    BackgroundWorker worker = sender as BackgroundWorker; 
    while(true) 
    { 
     if ((worker.CancellationPending == true)) 
     { 
      e.Cancel = true; 
      break; 
     } 
     else 
     { 
      string str = comm.ReadLine(); 
      //... 
     } 
    } 
} 

编辑:啊...只是使用http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived.aspx
不需要BackgroundWorker的

+0

这是MSDN的例子,当我看到这个if((worker.CancellationPending == true))时,我总是笑,应该是if(worker.CancellationPending == true) –

+0

我看不到您包含的代码中的任何全局变量都需要添加它,以便我们可以确切地看到它是什么类型。 – EkoostikMartin

+0

您是否尝试过设置DataReceived EventHandler。您可以在UI线程中读取串行端口。除非它显着影响你的用户界面。 –

回答

1

SerialPort.ReadLine()是一个阻塞调用。直到港口收到一行文字和一个NewLine,它才会返回。这不可避免地意味着您对CancellationPending的测试将不起作用,代码将停留在ReadLine()调用中。所以你会调用bgw的CancelAsync()调用,然后关闭串口。这会导致ReadLine()方法抛出异常。

没有好的方法可以干净地做到这一点,您没有任何其他方法来强制ReadLine()方法返回。因此,赶上例外情况,检查CancellationPending是否为真,并保持原样。

+0

当前超时设置为-1。 我第一次使用背景工作,所以我不知道我该怎么做。我只想读取接收到的字节,并将它们作为HEX和ASCII放在表中 – user1527484