I got global variable SerialPort comm; After opening com port im reading recived bytes and i get exception that com port is closed..
How can i access to it in backgroundworker correctly?
are there better way to declare comm?
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();
//...
}
}
}
EDIT: yea … just use this http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived.aspx
no need for BackgroundWorker
SerialPort.ReadLine() is a blocking call. It won’t return until the port has received a line of text and a NewLine. Which inevitably means that your test for CancellationPending will not work, the code is stuck in the ReadLine() call. So you’ll call the bgw’s CancelAsync() call and then close the serial port. And that causes the ReadLine() method to throw an exception.
There are no good ways to do this cleanly, you don’t have any other way to force the ReadLine() method to return. So catch the exception, check if CancellationPending is true and bail out when it is.