Prabal Kajla
Prabal Kajla

Reputation: 125

StreamReader await ReadLineAsync blocks execution

I have the following code in a desktop application :

using (StreamReader reader = new StreamReader("path\\to\\file.csv"))
{
    string line;
    while (!reader.EndOfStream)
    {
        line = await reader.ReadLineAsync();
        string[] values = line.Split(',');
        double.TryParse(values[pointsIndex], out double points);
    }
}

The line line = await reader.ReadLineAsync() blocks the the program entirely and makes the application unresponsive. While debugging I noticed that it is runs 4 times and then blocks indefinitely.

This code is very simple and correct AFAIK. Why is it not working as expected?

Upvotes: 1

Views: 3245

Answers (1)

Vytautas Plečkaitis
Vytautas Plečkaitis

Reputation: 861

Try to change it to

using (StreamReader reader = new StreamReader("path\\to\\file.csv"))
{
    string line;
    while ((line = await reader.ReadLineAsync()) != null)
    {
     string[] values = line.Split(',');
     double.TryParse(values[pointsIndex], out double points);
    }
}

When it hits end - result will be null and terminate. See the relative documentation here

Upvotes: 1

Related Questions