dotMorten / NmeaParser

Library for handling NMEA message in Windows Desktop, Store, Phone, Universal, and Xamarin (Android + iOS), coming from files, bluetooth, serial port or any stream
https://dotmorten.github.io/NmeaParser/
Apache License 2.0
262 stars 89 forks source link

Read task should end on exception #114

Closed ClemensFischer closed 2 weeks ago

ClemensFischer commented 8 months ago

When NmeaDevice.ReadAsync permanently throws an exception (e.g. because m_stream is broken), the read task started in NmeaDevice.StartParser goes into an endless empty loop with high CPU consumption.

The empty catch block (which is a bad thing anyway) should instead end the loop and signal the termination to the NmeaDevice instance, e.g. by raising a ReadFailed event.

private void StartParser(CancellationToken token)
{
    System.Diagnostics.Debug.WriteLine("Starting parser...");
    m_ParserTask = Task.Run(async () =>
    {
        byte[] buffer = new byte[1024];
        while (!token.IsCancellationRequested)
        {
            int readCount = 0;
            try
            {
                readCount = await ReadAsync(buffer, 0, 1024, token).ConfigureAwait(false);
            }
            catch { }
            if (token.IsCancellationRequested)
                break;
            if (readCount > 0)
            {
                OnData(buffer, readCount);
            }
            await Task.Yield();
        }
    });
}