次のコードがあります。
private void button1_Click(object sender, RoutedEventArgs e)
{
button1.IsEnabled = false;
var s = File.ReadAllLines("Words.txt").ToList(); // my WPF app hangs here
// do something with s
button1.IsEnabled = true;
}
Words.txt
s 変数に読み込んだ単語がたくさんあるので、C# 5 のasync
andキーワードを使ってWPF アプリがハングしないようにしています。これまでのところ、次のコードがあります。await
Async CTP Library
private async void button1_Click(object sender, RoutedEventArgs e)
{
button1.IsEnabled = false;
Task<string[]> ws = Task.Factory.FromAsync<string[]>(
// What do i have here? there are so many overloads
); // is this the right way to do?
var s = await File.ReadAllLines("Words.txt").ToList(); // what more do i do here apart from having the await keyword?
// do something with s
button1.IsEnabled = true;
}
目標は、WPF アプリのフリーズを回避するために、同期ではなく非同期でファイルを読み取ることです。
どのような助けでも大歓迎です、ありがとう!
ベストアンサー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
コードの臭い。
ブロッキング関数を使用してCPUスレッドを無駄にしたくない場合は、完全に非同期のIOメソッドを待機する必要があります。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();
}
}