3

我在这里有这个代码来读取文件:

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

我想为大文件异步读取文件,但不知道如何在这里执行。你能指出正确的方向吗?

这就是我试图使其异步的原因:

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

看来我的AddWords方法不起作用(使用异步时)。此方法将单词添加到字典中:

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

            }
        }
    }
4

1 回答 1

3

避免async void。返回方法的async等价物voidasync Task,不是async void

在使用字典之前更改private async void ReadFile()private async Task ReadFileAsync()和结果。await

于 2012-12-19T01:42:06.423 回答