Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading files asynchronously

I have this code here for reading files:

private void ReadFile()
{
    using (StreamReader reader = File.OpenText("data.txt"))
        {
            while ((currentline = reader.ReadLine()) != null)
            {
                currentline = currentline.ToLower();
                currentline = RemoveChars(currentline);
                currentline = RemoveShortWord(currentline);
                AddWords(currentline);
            }
        }
    }

I would like to read files asynchronous for large files but not sure how to do it here. Could you point in the right directions.

This is what I tried to make it asynchronous:

    private async void ReadFile()
    {

        using (StreamReader reader = File.OpenText("dickens.txt"))
        {
            while ((currentline =  await reader.ReadLineAsync()) != null)
            {
                currentline = currentline.ToLower();
                currentline = RemoveChars(currentline);
                currentline = RemoveShortWord(currentline);
                AddWords(currentline);
            }
        }
    }

It seem that my AddWords method is not working (when using asynchronous). This method adds words to a dictionary:

    private void AddWords(string line)
    {
        string[] word = line.Split(' ');

        foreach (string str in word)
        {
            if (str.Length >= 3)
            {
                if (dictionary.ContainsKey(str))
                {
                    dictionary[str]++;
                }
                else
                {
                    dictionary[str] = 1;
                }

            }
        }
    }

1 Answers

Avoid async void. The async equivalent of a method returning void is async Task, not async void.

Change private async void ReadFile() to private async Task ReadFileAsync() and await the result before using the dictionary.

like image 69
Stephen Cleary Avatar answered Mar 14 '26 08:03

Stephen Cleary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!