I am having issues with a program that is getting unreliable data from a serial port, and I believe https://www.sparxeng.com/blog/software/must-use-net-system-io-ports-serialport#comments
This article has some answers - the bytestoread value seems erratic, the callback isn't always called when data is there and all of the default serial port functions are unreliable, including the datareceived event. Exactly what I am experiencing in this program. In fact, all over the microsoft documentation for serial ports there are disclaimers and notes of failed functionality. What it doesn't have is solutions to these problems when they pop up in your applications.
However, when I attempt to use the provided solution in the article it seems to output the same first byte over and over forever: "pppppppppppppppppppppppppppp" I can confirm the first byte received is actually "p", but why it is not removing that byte after reading it and proceeding, or receiving any bytes after, I do not know. As far as I can tell it is the exact same solution proposed in the article. Here is the code:
private void Form1_Shown(object sender, EventArgs e)
{
try
{
sp.Open();
SPDataHelper();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void SPDataHelper()
{
byte[] buffer = new byte[8000];
Action kickoffRead = null;
kickoffRead = delegate
{
sp.BaseStream.BeginRead(buffer, 0, buffer.Length, delegate (IAsyncResult ar)
{
try
{
int actualLength = sp.BaseStream.EndRead(ar);
byte[] received = new byte[actualLength];
Buffer.BlockCopy(buffer, 0, received, 0, actualLength);
sp_DataReceived(System.Text.Encoding.UTF8.GetString(received));//not called by the actual serialport anymore
}
catch (IOException exc)
{
WriteUUTWindow("Exception: "+exc.ToString());
}
kickoffRead();
}, null);
};
kickoffRead();
}
When I put a breakpoint on the "actuallength" after its assignment it shows 1, suggesting it never reads after the first byte. The breakpoint for both that assignment and the callback are never reached again afterwards, but the application continues to spam "p". Any idea what's going on here?
If you're interested in using
BeginRead
, try the following - it's been tested with a barcode scanner:Create a class (name: HelperSerialPort.cs)
Option 1:
HelperSerialPort.cs
Update
Here's another version which seems to work as well-it uses a slightly modified version of your code.
Option 2:
HelperSerialPort.cs
Option 3
Here's an option that uses SerialPort
DataReceived
.HelperSerialPort.cs:
Usage:
Note: Ensure
Dispose
is called when you're finished with the SerialPort.