原文:https://msdn.microsoft.com/en-us/library/jj155757.aspx

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Text;
  6. using System.Threading.Tasks;
Writing Text

The following example writes text to a file. At each await statement, the method immediately exits. When the file I/O is complete, the method resumes at the statement that follows the await statement. Note that the async modifier is in the definition of methods that use the await statement.

  1. public async void ProcessWrite()
  2. {
  3. string filePath = @"temp2.txt";
  4. string text = "Hello World\r\n";
  5.  
  6. await WriteTextAsync(filePath, text);
  7. }
  8.  
  9. private async Task WriteTextAsync(string filePath, string text)
  10. {
  11. byte[] encodedText = Encoding.Unicode.GetBytes(text);
  12.  
  13. using (FileStream sourceStream = new FileStream(filePath,
  14. FileMode.Append, FileAccess.Write, FileShare.None,
  15. bufferSize: , useAsync: true))
  16. {
  17. await sourceStream.WriteAsync(encodedText, , encodedText.Length);
  18. };
  19. }

The original example has the statement await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);, which is a contraction of the following two statements:

  1. Task theTask = sourceStream.WriteAsync(encodedText, , encodedText.Length);
  2. await theTask;

The first statement returns a task and causes file processing to start. The second statement with the await causes the method to immediately exit and return a different task. When the file processing later completes, execution returns to the statement that follows the await. For more information, see Control Flow in Async Programs (C# and Visual Basic) and Walkthrough: Using the Debugger with Async Methods.

Reading Text

The following example reads text from a file. The text is buffered and, in this case, placed into a StringBuilder. Unlike in the previous example, the evaluation of the await produces a value. The ReadAsync method returns a Task<Int32>, so the evaluation of the await produces an Int32 value (numRead) after the operation completes. For more information, see Async Return Types (C# and Visual Basic).

  1. public async void ProcessRead()
  2. {
  3. string filePath = @"temp2.txt";
  4.  
  5. if (File.Exists(filePath) == false)
  6. {
  7. Debug.WriteLine("file not found: " + filePath);
  8. }
  9. else
  10. {
  11. try
  12. {
  13. string text = await ReadTextAsync(filePath);
  14. Debug.WriteLine(text);
  15. }
  16. catch (Exception ex)
  17. {
  18. Debug.WriteLine(ex.Message);
  19. }
  20. }
  21. }
  22.  
  23. private async Task<string> ReadTextAsync(string filePath)
  24. {
  25. using (FileStream sourceStream = new FileStream(filePath,
  26. FileMode.Open, FileAccess.Read, FileShare.Read,
  27. bufferSize: , useAsync: true))
  28. {
  29. StringBuilder sb = new StringBuilder();
  30.  
  31. byte[] buffer = new byte[0x1000];
  32. int numRead;
  33. while ((numRead = await sourceStream.ReadAsync(buffer, , buffer.Length)) != )
  34. {
  35. string text = Encoding.Unicode.GetString(buffer, , numRead);
  36. sb.Append(text);
  37. }
  38.  
  39. return sb.ToString();
  40. }
  41. }
 
Parallel Asynchronous I/O

The following example demonstrates parallel processing by writing 10 text files. For each file, the WriteAsync method returns a task that is then added to a list of tasks. The await Task.WhenAll(tasks); statement exits the method and resumes within the method when file processing is complete for all of the tasks.

The example closes all FileStream instances in a finally block after the tasks are complete. If each FileStream was instead created in a using statement, the FileStream might be disposed of before the task was complete.

Note that any performance boost is almost entirely from the parallel processing and not the asynchronous processing. The advantages of asynchrony are that it doesn’t tie up multiple threads, and that it doesn’t tie up the user interface thread.

  1. public async void ProcessWriteMult()
  2. {
  3. string folder = @"tempfolder\";
  4. List<Task> tasks = new List<Task>();
  5. List<FileStream> sourceStreams = new List<FileStream>();
  6.  
  7. try
  8. {
  9. for (int index = ; index <= ; index++)
  10. {
  11. string text = "In file " + index.ToString() + "\r\n";
  12.  
  13. string fileName = "thefile" + index.ToString("") + ".txt";
  14. string filePath = folder + fileName;
  15.  
  16. byte[] encodedText = Encoding.Unicode.GetBytes(text);
  17.  
  18. FileStream sourceStream = new FileStream(filePath,
  19. FileMode.Append, FileAccess.Write, FileShare.None,
  20. bufferSize: , useAsync: true);
  21.  
  22. Task theTask = sourceStream.WriteAsync(encodedText, , encodedText.Length);
  23. sourceStreams.Add(sourceStream);
  24.  
  25. tasks.Add(theTask);
  26. }
  27.  
  28. await Task.WhenAll(tasks);
  29. }
  30.  
  31. finally
  32. {
  33. foreach (FileStream sourceStream in sourceStreams)
  34. {
  35. sourceStream.Close();
  36. }
  37. }
  38. }

When using the WriteAsync and ReadAsync methods, you can specify a CancellationToken, which you can use to cancel the operation mid-stream. For more information, see Fine-Tuning Your Async Application (C# and Visual Basic) and Cancellation in Managed Threads.

转 Using Async for File Access的更多相关文章

  1. file access , argc, argv[ ]

    _____main函数含有 两个参数 ,argc ,argv[] 这两个参数用以指示命令行输入的参数信息. argc 的值是输入的参数的数量.argv是一个数组,每个数组元素指向一个string字符串 ...

  2. Method and system for implementing mandatory file access control in native discretionary access control environments

    A method is provided for implementing a mandatory access control model in operating systems which na ...

  3. Unable to copy file, Access to the path is denied

    Unable to copy file, Access to the path is denied http://stackoverflow.com/questions/7130136/unable- ...

  4. Samba set of user authentication and file access rights

    This series is compatible with Linux certification exam LPIC. A typical Linux user-level topics omit ...

  5. 编程概念--使用async和await的异步编程

    Asynchronous Programming with Async and Await You can avoid performance bottlenecks and enhance the ...

  6. C#的多线程——使用async和await来完成异步编程(Asynchronous Programming with async and await)

    https://msdn.microsoft.com/zh-cn/library/mt674882.aspx 侵删 更新于:2015年6月20日 欲获得最新的Visual Studio 2017 RC ...

  7. C# Async, Await and using statements

    Async, Await 是基于 .NEt 4.5架构的, 用于处理异步,防止死锁的方法的开始和结束, 提高程序的响应能力.比如: Application area           Support ...

  8. Linux File System Change Monitoring Technology、Notifier Technology

    catalog . 为什么要监控文件系统 : hotplug . udev . fanotify(fscking all notification system) . inotify . code e ...

  9. async源码学习 - 全部源码

    因为工作需要,可能我离前端走远了,偏node方向了.所以异步编程的需求很多,于是乎,不得不带着学习async了. 我有个习惯,用别人的东西之前,喜欢稍微搞明白点,so就带着看看其源码. github: ...

随机推荐

  1. 前端神器之jquery

    jquery介绍 jQuery是目前使用最广泛的javascript函数库.据统计,全世界排名前100万的网站,有46%使用jQuery,远远超过其他库.微软公司甚至把jQuery作为他们的官方库. ...

  2. js介绍,js三种引入方式,js选择器,js四种调试方式,js操作页面文档DOM(修改文本,修改css样式,修改属性)

    js介绍 js运行编写在浏览器上的脚本语言(外挂,具有逻辑性) 脚本语言:运行在浏览器上的独立的代码块(具有逻辑性) 操作BOM 浏览器对象盒子 操作DOM 文本对象 js三种引入方式 (1)行间式: ...

  3. DUMP4 企业级电商项目 —— 对接支付宝扫码支付

    延展 <谈谈微信支付曝出的漏洞> [联调 DEMO下载地址]https://docs.open.alipay.com/194/105201/ [内置 一份 说明文档可做参考] [impor ...

  4. Codeforces Round #501 (Div. 3) D. Walking Between Houses

    题目链接 题意:给你三个数n,k,sn,k,sn,k,s,让你构造一个长度为k的数列,使得相邻两项差值的绝对值之和为sss, ∑i=1n∣a[i]−a[i−1]∣,a[0]=1\sum_{i=1}^n ...

  5. python中字符串编码转换

    字符串编码转换程序员最苦逼的地方,什么乱码之类的几乎都是由汉字引起的. 其实编码问题很好搞定,只要记住一点: 任何平台的任何编码,都能和Unicode互相转换. UTF-8与GBK互相转换,那就先把U ...

  6. 全平台网页播放器兼容H5与Flash还带播放列表

    许久不发文了,2018年第一篇文章,写点干货--关于网页播放器的问题.嗯,实际上我是在52破解首发的,当做新人贴. 目前来说,网页播放器不少,随便找找都能找到一大堆,然而好用的就那么几个,比如ckpl ...

  7. greenplum加密

    --如下为greenplum5.0数据库加解密--加密函数select encrypt('123456','aa','aes');--加解密函数select convert_from(decrypt( ...

  8. 点击页面上的元素,页面删除removeChild()

    简单描述:最近做了一个图片上传,上传完成回显图片的时候,需要用到点击图片,从页面删除的效果,然后就找到了removeChild()方法,说实话,我刚看到的时候,就觉得这个问题已经解决了,但是却发现这个 ...

  9. SSH 架构

    这几天学习了 ssh 架构,中间出了好多错误,现在终于整理好了,就记录下来 ssh机构的框架构成,以及它们的作用 struts2 :这个框架主要用做控制处理的,其核心是 Contraller ,即 A ...

  10. Matlab将多项式的系数设为0

    符号运算时有些多项式的系数值接近于0,像这样 fun = 3.5753839759325595498222646101085e-49*x + 1.836709923159824231201150839 ...