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?
I think its better to use ManualResetEvent
. This way your thread will wake up on cancellation instead of sleeping for 10 ms.
do
{
var ftdiStatus = ftdiDevice.GetRxBytesWaiting(ref rxBytes);
if (ftdiStatus != FTDI.FT_STATUS.FT_OK)
return null;
if (rxBytes >= dataBlockSize)
break;
}
while (!cancelEvent.WaitOne(10));