Main Site Documentation

Is it OK to busywait on USB host pipes?


#1

In my code I have a loop:

private static void DoProtocol(USBH_RawDevice.Pipe inPipe, USBH_RawDevice.Pipe outPipe)
{
    var inBuffer = new byte[inPipe.PipeEndpoint.wMaxPacketSize];
    var outBuffer = new byte[outPipe.PipeEndpoint.wMaxPacketSize];
    int bytesTransferred;

    while (true)
    {
        bytesTransferred = inPipe.TransferData(inBuffer, 0, 1);
        if (bytesTransferred > 0)
        {
           // Do stuff 
        }
    }
}

Is there an efficient blocking way to do this? That is, most of the time TransferData is returning 0 and nothing needs to be done, so the loop is just spinning.


#2

I assume it is on a separate thread. You can sleep a little bit at the end of the loop.


#3

Not sure how TransferTimeout factors in here. But it’s not clear what the right answer is. I’m happy with spinning in a loop forever, but if that’s not the right way to do it, I’d take an alternative. It sounds like “that’s the right way to do it”.


#4

You should have a sleep in the loop. The sleep time is the max number you can work with in your app