转 Using Async for File Access
原文:https://msdn.microsoft.com/en-us/library/jj155757.aspx
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
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.
public async void ProcessWrite()
{
string filePath = @"temp2.txt";
string text = "Hello World\r\n"; await WriteTextAsync(filePath, text);
} private async Task WriteTextAsync(string filePath, string text)
{
byte[] encodedText = Encoding.Unicode.GetBytes(text); using (FileStream sourceStream = new FileStream(filePath,
FileMode.Append, FileAccess.Write, FileShare.None,
bufferSize: , useAsync: true))
{
await sourceStream.WriteAsync(encodedText, , encodedText.Length);
};
}
The original example has the statement await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);, which is a contraction of the following two statements:
Task theTask = sourceStream.WriteAsync(encodedText, , encodedText.Length);
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.
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).
public async void ProcessRead()
{
string filePath = @"temp2.txt"; if (File.Exists(filePath) == false)
{
Debug.WriteLine("file not found: " + filePath);
}
else
{
try
{
string text = await ReadTextAsync(filePath);
Debug.WriteLine(text);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
} private async Task<string> ReadTextAsync(string filePath)
{
using (FileStream sourceStream = new FileStream(filePath,
FileMode.Open, FileAccess.Read, FileShare.Read,
bufferSize: , useAsync: true))
{
StringBuilder sb = new StringBuilder(); byte[] buffer = new byte[0x1000];
int numRead;
while ((numRead = await sourceStream.ReadAsync(buffer, , buffer.Length)) != )
{
string text = Encoding.Unicode.GetString(buffer, , numRead);
sb.Append(text);
} return sb.ToString();
}
}
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.
public async void ProcessWriteMult()
{
string folder = @"tempfolder\";
List<Task> tasks = new List<Task>();
List<FileStream> sourceStreams = new List<FileStream>(); try
{
for (int index = ; index <= ; index++)
{
string text = "In file " + index.ToString() + "\r\n"; string fileName = "thefile" + index.ToString("") + ".txt";
string filePath = folder + fileName; byte[] encodedText = Encoding.Unicode.GetBytes(text); FileStream sourceStream = new FileStream(filePath,
FileMode.Append, FileAccess.Write, FileShare.None,
bufferSize: , useAsync: true); Task theTask = sourceStream.WriteAsync(encodedText, , encodedText.Length);
sourceStreams.Add(sourceStream); tasks.Add(theTask);
} await Task.WhenAll(tasks);
} finally
{
foreach (FileStream sourceStream in sourceStreams)
{
sourceStream.Close();
}
}
}
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的更多相关文章
- file access , argc, argv[ ]
_____main函数含有 两个参数 ,argc ,argv[] 这两个参数用以指示命令行输入的参数信息. argc 的值是输入的参数的数量.argv是一个数组,每个数组元素指向一个string字符串 ...
- 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 ...
- 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- ...
- 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 ...
- 编程概念--使用async和await的异步编程
Asynchronous Programming with Async and Await You can avoid performance bottlenecks and enhance the ...
- 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 ...
- C# Async, Await and using statements
Async, Await 是基于 .NEt 4.5架构的, 用于处理异步,防止死锁的方法的开始和结束, 提高程序的响应能力.比如: Application area Support ...
- Linux File System Change Monitoring Technology、Notifier Technology
catalog . 为什么要监控文件系统 : hotplug . udev . fanotify(fscking all notification system) . inotify . code e ...
- async源码学习 - 全部源码
因为工作需要,可能我离前端走远了,偏node方向了.所以异步编程的需求很多,于是乎,不得不带着学习async了. 我有个习惯,用别人的东西之前,喜欢稍微搞明白点,so就带着看看其源码. github: ...
随机推荐
- springBoot总结
springBoot总结: ssm基本的依赖: <dependencies> <!--添加依赖thymeleaf 可以访问html页面--> <!--<depend ...
- Vim使用技巧:将Tab转换为4个空格
一 Tab转成4个空格 为了防止因为在不同系统中Tab键的宽度不一致而导致代码缩进显示混乱的情况,有必要将Tab键转换成空格,推荐的空格数为4.将下面的代码写入你的.vimrc文件中即可实现在Vim编 ...
- python chrome的自定义启动
# encoding:utf-8 """@version: python27@author: fafa@site: http://www.phpgao.com@softw ...
- 使用PHP中的ajax做登录页面、验证用户名是否可用、动态调用数据库
1.ajax的基础知识 ajax是结合了jquery.php等几种技术延伸出来的综合运用的技术,不是新的内容.ajax也是写在<script>标签里面的. 如果使用ajax一定是要有1个处 ...
- Arduino传感器学习目录
Arduino-接口图 在Windows上安装Arduino-IDE 函数库和程序架构介绍 Arduino语法-变量和常量 Arduino常用的数据类型以及转换 Arduino—运算符 ...
- 用sklearn 实现linear regression
基本的regression算法有四种方法可以实现,分别是下面四种 LinearRegressionRidge (L2 regularization)Lasso (L1 regularization)E ...
- VS2012遇到一个问题:"链接器工具错误 LNK2026 XXX模块对于 SAFESEH 映像是不安全的"
解决方法: 1.打开该项目的“属性页”对话框. 2.单击“链接器”文件夹. 3.单击“命令行”属性页. 4.将 /SAFESEH:NO 键入“附加选项”框中,然后点击应用.
- 记录一次Python下Tensorflow安装过程,1.7带GPU加速版本
最近由于论文需要,急需搭建Tensorflow环境,16年底当时Tensorflow版本号还没有过1,我曾按照手册搭建过CPU版本.目前,1.7算是比较新的版本了(也可以从源码编译1.8版本的Tens ...
- Linux日志每日备份脚本
2018-5-28 10:59:07 星期一 原理是: 1. 每天0点0分crontab执行备份脚本 2. 先将当前日志文件copy一份作为备份, 备份文件名的后缀为前一天 3. 用当前日志的最后50 ...
- 【转】Java中文乱码的解决
在基于Java的编程中,经常会碰到汉字的处里及显示的问题,比如一大堆乱码或问号. 这是因为JAVA中默认的编码方式是UNICODE,而中国人通常使用的文件和DB都是基于GB2312或者BIG5等编码, ...