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;
}
Task<T>
is for an eventual result, not one that happens periodically. – UcayaliThread
for this kind of task?Task
s are designed to finish quickly, while your IO could take minutes – Pithead