我得到了全局变量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的
这是MSDN的例子,当我看到这个if((worker.CancellationPending == true))时,我总是笑,应该是if(worker.CancellationPending == true) –
我看不到您包含的代码中的任何全局变量都需要添加它,以便我们可以确切地看到它是什么类型。 – EkoostikMartin
您是否尝试过设置DataReceived EventHandler。您可以在UI线程中读取串行端口。除非它显着影响你的用户界面。 –