转 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: ...
随机推荐
- [物理学与PDEs]第3章习题6 Lagrange 坐标下的一维理想磁流体力学方程组的数学结构
试讨论 Lagrange 形式下的一维理想磁流体力学方程组 (5. 33)-(5. 39) 的类型. 解答: 由 (5. 33), (5. 39) 知 $$\bex 0=\cfrac{\p p}{\p ...
- java8 按对象属性值排序
//按id从小到大 List<User> sortUser = list.stream().sorted((u1, u2) -> u1.getId().compareTo(u2.ge ...
- Vue导出json数据到Excel表格
一.安装依赖 npm install file-saver --save npm install xlsx --save npm install script-loader --save-dev 二. ...
- Linux 之 rsyslog+mysql+LogAnalyzer 日志收集系统
作者:邓聪聪 LogAnalyzer 是一个 syslog 和其他网络事件数据的 Web 前端工具,提供简单易用的日志浏览.搜索和基本分析以及图表显示 由于公司部分项目需求使用日志记录系统,随笔记录 ...
- Django的邮件发送以及云服务器上遇到的问题
邮件发送 首先我们的邮箱要开通smtp服务,然后就可以在settings中配置了 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBacken ...
- 【原创】大叔经验分享(16)Context namespace element 'component-scan' and its parser class [org.springframework.context.annotation.ComponentScanBeanDefinitionParser] are only available on JDK 1.5 and higher
今天尝试运行一个古老的工程,配置好之后编译通过,结果运行时报错: org.springframework.beans.factory.BeanDefinitionStoreException: Une ...
- storage和memory
memory:使用的是值传递,默认使用的是memory,传递的是值 storage:引用传递,传过来的是指针,后面一定要加上internal,private pragma solidity ^; co ...
- js在数组arr中随机获取count数量的元素
// 在数组arr中随机获取count数量的元素; const getRandomArrayElements = (arr, num) => { // 新建一个数组,将传入的数组复制过来,用于运 ...
- js编译原理(你不知道的javascript)
虽然通常将js归类为"动态"或"解释执行"语言,但其实也可把它看成是一门编译语言.只不过这个所谓的编译与传统的编译语言不同,它不是提前编译的,编译结果也不能在分 ...
- Windows Internals 笔记——进程的权限
1.大多数用户都用一个管理员账户来登录Windows,在Vista之前,这样的登录会创建一个安全令牌.每当有代码试图使用一个受保护的安全资源时,操作系统就会出示这个令牌.从包括Windows资源管理器 ...