我在这里有这个代码来读取文件:
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;
}
}
}
}