【C#】62.异步读写⽂件的⼏种⽅法:Task.Factory.FromAsync,Wri。
。。
⼀、这⾥主要说明2种异步写⼊⽂件的⽅法:
1)异步编程模型API转为Task——使⽤Task.Factory.FromAsync⽅法
2)对于StreamWriter使⽤WriteAsync⽅法
请记得对stream对象使⽤FileOptions.Asynchronous选项!
⾸先来看⼀下准备函数:
CreateFileContent是⽤来随机⽣成要写⼊的内容(字符串形式);
SumFileContent
[csharp]
1. static string CreateFileContent()
2. {
3. var sb = new StringBuilder();
4. for (int i = 0; i < 100000; i++)
5. {
6. sb.AppendFormat("{0}", new Random(i).Next(0, 99999));
7. sb.AppendLine();
8. }
9. return sb.ToString();
10. }
11.
12. async static Task<long> SumFileContent(string fileName)
13. {
14. using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read,FileShare.None, BUFFER_SIZE, FileOptions.Asynchronous))
15. using (var sr = new StreamReader(stream))
16. {
17. long sum = 0;
18. while (sr.Peek() > -1)
19. {
20. string line = await sr.ReadLineAsync();
21. sum += long.Parse(line);
22. }
23.
24. return sum;
25. }
26. }
27.
28. static Task SimulateAsynchronousDelete(string fileName)
29. {
30. return Task.Run(() => File.Delete(fileName));
31. }
1)Task.Factory.FromAsync⽅法
[csharp]
1. using (var stream = new FileStream("test
<", FileMode.Create, FileAccess.ReadWrite, FileShare.None, BUFFER_SIZE, FileOptions.Asynchronous))
2. {
3. Console.WriteLine("2. Uses I/O Threads: {0}", stream.IsAsync);
4. byte[] buffer = Encoding.UTF8.GetBytes(CreateFileContent());
5. var writeTask = Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, buffer, 0, buffer.Length, null);
6.
7. await writeTask;
8. }
2)StreamWriter.WriteAsync⽅法
[csharp]
1. using (var stream = File.Create("", BUFFER_SIZE, FileOptions.Asynchronous))
2. using (var sw = new StreamWriter(stream))
3. {
4. Console.WriteLine("3. Uses I/O Threads: {0}", stream.IsAsync);
5. await sw.WriteAsync(CreateFileContent());
6. }
⼆、异步从⽂件中读取内容(四个Task来数字数,WhenAll后再相加)
[csharp]
1. Console.WriteLine("Starting parsing files in parallel");
2.
3. Task<long>[] readTasks = new Task<long>[4];
4. for (int i = 0; i < 4; i++)
5. {
6. readTasks[i] = SumFileContent(string.Format("test{0}.txt", i + 1));
7. }
8.
9. long[] sums = await Task.WhenAll(readTasks);
10.
11. Console.WriteLine("Sum in all files: {0}", sums.Sum());
三、模拟异步删除(因为API中没有异步删除)
[csharp]
1. Console.WriteLine("");
log4j2 异步写文件
2.
3. Task[] deleteTasks = new Task[4];
4. for (int i = 0; i < 4; i++)
5. {
6. string fileName = string.Format("test{0}.txt", i + 1);
7. deleteTasks[i] = SimulateAsynchronousDelete(fileName);
8. }
9.
10. await Task.WhenAll(deleteTasks);
11.
12. Console.WriteLine("Deleting complete.");

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。