一、这里主要说明2种异步写入文件的方法:
1)异步编程模型API转为Task——使用Task.Factory.FromAsync方法
2)对于StreamWriter使用WriteAsync方法
请记得对stream对象使用FileOptions.Asynchronous选项!
首先来看一下准备函数:
CreateFileContent是用来随机生成要写入的内容(字符串形式);
SumFileContent
static string CreateFileContent()
{
var sb = new StringBuilder();
for (int i = 0; i < 100000; i++)
{
sb.AppendFormat("{0}", new Random(i).Next(0, 99999));
sb.AppendLine();
}
return sb.ToString();
}
async static Task SumFileContent(string fileName)
{
using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read,FileShare.None, BUFFER_SIZE, FileOptions.Asynchronous))
using (var sr = new StreamReader(stream))
{
long sum = 0;
while (sr.Peek() > -1)
{
string line = await sr.ReadLineAsync();
sum += long.Parse(line);
}
return sum;
}
}
static Task SimulateAsynchronousDelete(string fileName)
{
return Task.Run(() => File.Delete(fileName));
}
using (var stream = new FileStream("test2.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.None, BUFFER_SIZE, FileOptions.Asynchronous))
{
Console.WriteLine("2. Uses I/O Threads: {0}", stream.IsAsync);
byte[] buffer = Encoding.UTF8.GetBytes(CreateFileContent());
var writeTask = Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, buffer, 0, buffer.Length, null);
await writeTask;
}
using (var stream = File.Create("test3.txt", BUFFER_SIZE, FileOptions.Asynchronous))
using (var sw = new StreamWriter(stream))
{
Console.WriteLine("3. Uses I/O Threads: {0}", stream.IsAsync);
await sw.WriteAsync(CreateFileContent());
}
二、异步从文件中读取内容(四个Task来数字数,WhenAll后再相加)
Console.WriteLine("Starting parsing files in parallel");
Task[] readTasks = new Task[4];
for (int i = 0; i < 4; i++)
{
readTasks[i] = SumFileContent(string.Format("test{0}.txt", i + 1));
}
long[] sums = await Task.WhenAll(readTasks);
Console.WriteLine("Sum in all files: {0}", sums.Sum());
Console.WriteLine("Deleting files...");
Task[] deleteTasks = new Task[4];
for (int i = 0; i < 4; i++)
{
string fileName = string.Format("test{0}.txt", i + 1);
deleteTasks[i] = SimulateAsynchronousDelete(fileName);
}
await Task.WhenAll(deleteTasks);
Console.WriteLine("Deleting complete.");