HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Waiting for bytes to be ready

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
waitingbytesforready

Problem

What this should do is wait for dataBlockSize bytes to be ready and then continue, but wait for 10ms if they are not ready yet to not block the CPU, but not the first time as I do not want to wait once even if the bytes are ready.

Is there a better way of doing this?

while (!cancellationToken.IsCancellationRequested)
{                   
    var ftdiStatus = ftdiDevice.GetRxBytesWaiting(ref rxBytes);
    if (ftdiStatus != FTDI.FT_STATUS.FT_OK)
        return null;

    if (rxBytes >= dataBlockSize)
        break;

    Thread.Sleep(10);
}

Solution

I think it is just a matter of taste. Here is one approach:

do
{
    var ftdiStatus = FtdiDevice.FtdiDevice.Instance.GetRxBytesWaiting(ref rxBytes);

    if (ftdiStatus != FTDI.FT_STATUS.FT_OK)
        return null;

    if(rxBytes >= dataBlockSize)
        break;

    Thread.Sleep(10);
}
while (true); // Perhaps a check for timeout?

Code Snippets

do
{
    var ftdiStatus = FtdiDevice.FtdiDevice.Instance.GetRxBytesWaiting(ref rxBytes);

    if (ftdiStatus != FTDI.FT_STATUS.FT_OK)
        return null;

    if(rxBytes >= dataBlockSize)
        break;

    Thread.Sleep(10);
}
while (true); // Perhaps a check for timeout?

Context

StackExchange Code Review Q#31040, answer score: 3

Revisions (0)

No revisions yet.