Continuous polling using Tasks

Eternal21 picture Eternal21 · Jan 13, 2017 · Viewed 7.4k times · Source

This is something I've always used Threads / BackgroundWorker for, but am trying to migrate over to Task way of doing things.

Let's say I have a 3rd party SDK I use to read bytes from a USB port. That read call is blocking and times out after 100 ms if no bytes are read, returning null. It returns immediately if bytes are read, returning byte[] array of read bytes.

So I basically need to keep polling over and over, and take action on received bytes, by calling Parsing function. It's a WPF application, so the returned bytes should be able to be passed to a UI thread function.

What's the right approach to doing this? This is what I have so far, and it seems to work, but I want to make sure it's the right way of doing things using TPL:

private void _connectUsbButton_Click(object sender, RoutedEventArgs e)
{
   ListenForUsbMessagesAsync();
}

private async void ListenForUsbMessagesAsync()
{
    while (true)
    {
        byte[] readBytes = await ReadBytesAsync();
        Parse(readBytes);
    }
}

private Task<byte[]> ReadBytesAsync()
{
    Task<byte[]> readBytesTask = Task.Run(() =>
    {
        byte[] bytes;

        do
        {
            bytes = ReadBytes();
        } while (bytes == null);

        return bytes;
    });

    return readBytesTask;
}

private byte[] ReadBytes()
{
   byte[] readBytes = _usbSdk.ReadBytes(); //100ms timeout (returns null if no bytes read)
   return readBytes;
}

Answer

Matteo Marciano - MSCP picture Matteo Marciano - MSCP · Jan 13, 2017

Looks ok to me, just few suggestions here:

private async Task ListenForUsbMessagesAsync(CancellationToken token)
{
    while (true)
    {
        byte[] readBytes = await ReadBytesAsync();
        Parse(readBytes);
        token.ThrowIfCancellationRequested();
    }
}

Somewhere else, like in WPF Window .ctor store this

var tokenSource = new System.Threading.CancellationTokenSource();

Finally call your function like this

 private void _connectUsbButton_Click(object sender, RoutedEventArgs e)
 {
    ListenForUsbMessagesAsync(tokenSource.Token);
 }

This way you can cancel your task in any moment by calling

tokenSource.Cancel()

Alternatively, if you don't want to use Tasks, you can spawn a new Thread and pass in the Dispatcher object. In this way, the newly created Thread can fire stuff onto the UI Thread safely.