Ответ 1
ОБНОВЛЕНИЕ: асинхронные версии File.ReadAll[Lines|Bytes|Text]
, File.AppendAll[Lines|Text]
и File.WriteAll[Lines|Bytes|Text]
теперь объединены в .NET Core и поставляются с .NET Core 2.0. Они также включены в .NET Standard 2.1.
Использование Task.Run
, который по сути является оболочкой для Task.Factory.StartNew
, для асинхронных оболочек является запахом кода.
Если вы не хотите тратить поток ЦП с помощью функции блокировки, вам следует дождаться действительно асинхронного метода ввода-вывода, StreamReader.ReadToEndAsync
, например:
using (var reader = File.OpenText("Words.txt"))
{
var fileText = await reader.ReadToEndAsync();
// Do something with fileText...
}
Это получит весь файл как string
вместо List<string>
. Если вам нужны строки вместо этого, вы можете легко разделить строку, например, так:
using (var reader = File.OpenText("Words.txt"))
{
var fileText = await reader.ReadToEndAsync();
return fileText.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
}
РЕДАКТИРОВАТЬ: Вот несколько способов получить тот же код, что и в File.ReadAllLines
, но по-настоящему асинхронно. Код основан на реализации самого File.ReadAllLines
:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
public static class FileEx
{
/// <summary>
/// This is the same default buffer size as
/// <see cref="StreamReader"/> and <see cref="FileStream"/>.
/// </summary>
private const int DefaultBufferSize = 4096;
/// <summary>
/// Indicates that
/// 1. The file is to be used for asynchronous reading.
/// 2. The file is to be accessed sequentially from beginning to end.
/// </summary>
private const FileOptions DefaultOptions = FileOptions.Asynchronous | FileOptions.SequentialScan;
public static Task<string[]> ReadAllLinesAsync(string path)
{
return ReadAllLinesAsync(path, Encoding.UTF8);
}
public static async Task<string[]> ReadAllLinesAsync(string path, Encoding encoding)
{
var lines = new List<string>();
// Open the FileStream with the same FileMode, FileAccess
// and FileShare as a call to File.OpenText would've done.
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize, DefaultOptions))
using (var reader = new StreamReader(stream, encoding))
{
string line;
while ((line = await reader.ReadLineAsync()) != null)
{
lines.Add(line);
}
}
return lines.ToArray();
}
}