转 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: ...
随机推荐
- centos7项目部署
1. 安装nginx 添加CentOS 7 Nginx yum资源库 sudo rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/ng ...
- 纯js Ajax 请求
var XMLHttpReq; function createXMLHttpRequest() { if(window.ActiveXObject ) { try { XMLHttpReq = new ...
- LFYZ-OJ ID: 1015 统计数字(NOIP2007)
分析 本体思路很简单:读入数据,排序.统计.输出.难点在于数据量较大,选择何种排序方法就极为重要,否则很容易发生内存或时间超限.可以考虑以下几种思路: 桶排序 桶排序是可以想到的最简单方法,可在O(n ...
- 深入学习css伪类和伪元素及其用法
前言 CSS的伪类和伪元素在平时的代码中经常会出现,可是一旦别人问你,什么是伪类,什么是伪元素,可能还是不能完整的表述出来,下面我们来一探究竟. 伪类和伪元素定义 伪类用于在页面中的元素处于某个状态时 ...
- [物理学与PDEs]第1章第8节 静电场和静磁场 8.2 稳定电流的电场
1. 此时, Maxwell 方程组为 $$\beex \bea \Div{\bf D}&=\rho_f,\\ \rot {\bf E}&={\bf 0},\\ \Div{\bf B} ...
- EffectiveC++ 第3章 资源管理
我根据自己的理解,对原文的精华部分进行了提炼,并在一些难以理解的地方加上了自己的"可能比较准确"的「翻译」. Chapter 3 资源管理 条款13: 以对象管理资源 有时即使你顺 ...
- RT-SA-2019-004 Cisco RV320 Unauthenticated Diagnostic DataRetrieval
Advisory: Cisco RV320 Unauthenticated Diagnostic Data Retrieval RedTeam Pentesting discovered that t ...
- 【Java】Java随手记
System.out.printf() : System.out.printf("%d",x); 输出整数 System.out.printf(&quo ...
- ModuleNotFoundError: No module named '_sqlite3' -- python2.7 问题
ModuleNotFoundError: No module named '_sqlite3' 运行python 工程出现上面这个问题,以为python安装中缺少这个依赖, 注python 2.7 首 ...
- FTP:mget匹配文件名后下载
需求:从FTP某目录取每日构建的apk下载到本地 难点:文件名中有构建时间,而这个时间不算固定值,因此文件名不固定 解决方案:mget匹配文件名后下载 BAT版本: :: Filename:Proje ...