user751651
user751651

Reputation:

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;
                }

            }
        }
    }

Upvotes: 3

Views: 1775

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456332

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.

Upvotes: 3

Related Questions