It looks good, just a 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, save this
var tokenSource = new System.Threading.CancellationTokenSource();
Finally call your function as follows
private void _connectUsbButton_Click(object sender, RoutedEventArgs e) { ListenForUsbMessagesAsync(tokenSource.Token); }
This way you can cancel your task at any time by calling
tokenSource.Cancel()
Alternatively, if you do not want to use Tasks, you can create a new thread and pass a Dispatcher object. In this way, the newly created stream can safely write material to the user interface stream.
source share